如何在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 );
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 );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用反射。
其中
Foo
是someFunction
所需的参数类型。请注意,如果someFunction
接受一个object
,则不需要强制转换。如果类型是值类型,那么您需要使用(Foo)propertyB.GetValue(classB,null)
来转换它。我假设我们正在处理属性,而不是字段。如果情况并非如此,那么您可以更改为使用字段方法而不是属性,但您可能应该改用属性,因为字段通常不应该是公共的。
如果类型不兼容,即,
someFunction
不返回A
属性的类型或者它不可分配,那么您需要转换为正确的类型。同样,如果 B 的类型与函数的参数不兼容,您需要执行相同的操作。You need to use reflection.
where
Foo
is the type of the parameter thatsomeFunction
requires. Note that ifsomeFunction
takes anobject
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 ofA
'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.