c# - 如何在C#中通过字符串访问类成员?

标签 c# class reflection

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

例如如果静态代码是:

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,则不需要强制转换。如果类型是值类型,那么您需要使用 (Foo)propertyB.GetValue(classB,null) 来转换它。

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

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

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

关于c# - 如何在C#中通过字符串访问类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8953605/

相关文章:

reflection - 如果我知道函数的名称,是否可以获取其参数?

c# - dynamic 关键字是否*仅*用于动态语言?

c# - 错误CS0135 : 'Model' conflicts with the declaration 'System.Web.Mvc.ViewPage<TModel>.Model'

c# - MySql 执行时出现 ArgumentOutOfRangeException。 (MySqlConnector.NET)

c# - 反射 C# : Create instance of an object which has no default constructor

c# - 我可以要求 child 初始化在其父类中声明的变量吗?

C++ 类访问说明符详细程度

c++ - 如何在对象定义时将值发送给多个构造函数?

ruby-on-rails - Ruby -::in 类名

java - 覆盖 jdbc 第三方 jar 中的方法