加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:27:13 所属栏目:百科 来源:网络整理
导读:有没有办法通过字符串(名称)访问成员? 例如.如果静态代码是: classA.x = someFunction(classB.y); 但我只有两个字符串: string x = "x";string y = "y"; 我知道在JavaScript中你可以做到: classA[x] = someFunction(classB[y]); 但是如何在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,null) as Foo ),null );

其中Foo是someFunction所需参数的类型.请注意,如果someFunction采用对象,则不需要强制转换.如果类型是值类型,那么您将需要使用(Foo)propertyB.GetValue(classB,null)来代替它.

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读