微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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() );

原文地址:https://www.jb51.cc/csharp/91550.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐