如何在C#中按字符串访问类成员?

有没有办法通过字符串(名称)访问成员?

例如,如果静态代码是:

classA.x = someFunction(classB.y); 

但我只有两个字符串:

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

我知道在JavaScript中你可以做到:

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

但是如何在C#中做到这一点?

另外,是否可以按字符串定义名称?

例如:

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

更新 ,对于tvanfosson,我无法让它工作,它是:

 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 ); 

你需要使用reflection 。

  var propertyB = classB.GetType().GetProperty(y); var propertyA = classA.GetType().GetProperty(x); propertyA.SetValue( classA, someFunction( propertyB.GetValue(classB,null) as Foo ), null ); 

其中FoosomeFunction所需参数的类型。 请注意,如果someFunction采用object ,则someFunction 。 如果类型是值类型,那么您将需要使用(Foo)propertyB.GetValue(classB,null)来代替它。

我假设我们正在处理属性,而不是字段。 如果不是这种情况,那么您可以更改为使用字段的方法而不是属性,但您可能应该切换到使用属性,因为字段通常不应该是公共的。

如果类型不兼容,即someFunction不返回A属性的类型或者它不可分配,那么您需要转换为正确的类型。 同样,如果B的类型与函数的参数不兼容,则需要执行相同的操作。

  propetyA.SetValue( classA, someFunction(Convert.ToInt32( propertyB.GetValue(classB,null))).ToString() );