How to access class member by string in C#?

2019-01-25 14:06发布

Is there a way to access member by a string (which is the name)?

E.g. if static code is:

classA.x = someFunction(classB.y);

but I only have two strings:

string x = "x";
string y = "y";

I know in JavaScript you can simply do:

classA[x] = someFunction(classB[y]);

But how to do it in C#?

Also, is it possible to define name by string?

For example:

string x = "xxx";
class{
   bool x {get;set}  => means bool xxx {get;set}, since x is a string
}

UPDATE, to tvanfosson, I cannot get it working, it is:

public class classA
{
    public string A { get; set; }
}
public class classB
{
    public int B { get; set; }
}

var propertyB = classB.GetType().GetProperty("B");
var propertyA = classA.GetType().GetProperty("A");
propertyA.SetValue( classA, someFunction( propertyB.GetValue(classB, null) as string ), null );

1条回答
倾城 Initia
2楼-- · 2019-01-25 14:39

You need to use reflection.

 var propertyB = classB.GetType().GetProperty(y);
 var propertyA = classA.GetType().GetProperty(x);

 propertyA.SetValue( classA, someFunction( propertyB.GetValue(classB,null) as Foo ), null );

where Foo is the type of the parameter that someFunction requires. Note that if someFunction takes an object you don't need the cast. If the type is a value type then you'll need to use (Foo)propertyB.GetValue(classB,null) to cast it instead.

I'm assuming that we are working with properties, not fields. If that's not the case then you can change to use the methods for fields instead of properties, but you probably should switch to using properties instead as fields shouldn't typically be public.

If the types aren't compatible, i.e., someFunction doesn't return the type of A's property or it's not assignable, then you'll need to do a conversion to the proper type. Similarly if the type of B isn't compatible with the parameter of the function, you'll need to do the same thing.

 propetyA.SetValue( classA, someFunction(Convert.ToInt32( propertyB.GetValue(classB,null))).ToString() );
查看更多
登录 后发表回答