Don*_*own 2 c# reflection system.reflection
有没有办法用变量引用属性名称?
场景:对象A具有公共整数属性X和Z,所以......
public void setProperty(int index, int value)
{
string property = "";
if (index == 1)
{
// set the property X with 'value'
property = "X";
}
else
{
// set the property Z with 'value'
property = "Z";
}
A.{property} = value;
}
Run Code Online (Sandbox Code Playgroud)
这是一个愚蠢的例子,所以请相信,我有一个用途.
tuk*_*aef 23
简单:
a.GetType().GetProperty("X").SetValue(a, value);
Run Code Online (Sandbox Code Playgroud)
请注意,如果type类型没有名为"X"的属性,则GetProperty("X")返回.nulla
要在您提供的语法中设置属性,只需编写扩展方法:
public static class Extensions
{
public static void SetProperty(this object obj, string propertyName, object value)
{
var propertyInfo = obj.GetType().GetProperty(propertyName);
if (propertyInfo == null) return;
propertyInfo.SetValue(obj, value);
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
a.SetProperty(propertyName, value);
Run Code Online (Sandbox Code Playgroud)
UPD
请注意,这种基于反射的方法相对较慢.为了更好的性能,请使用动态代码生成或表达式树 有很好的库可以为你做这个复杂的东西.例如,FastMember.
我想你的意思是反思:
PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty");
info.SetValue(myObject, myValue);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15130 次 |
| 最近记录: |