我知道我的C#类中的一个属性的名称。是否有可能使用反射来设置此属性的值?我可以用反射设置属性值吗?
例如,说我知道一个属性的名称是string propertyName = "first_name";
。在那里有一个名为first_name
的房产。我可以使用这个字符串来设置它吗?
我知道我的C#类中的一个属性的名称。是否有可能使用反射来设置此属性的值?我可以用反射设置属性值吗?
例如,说我知道一个属性的名称是string propertyName = "first_name";
。在那里有一个名为first_name
的房产。我可以使用这个字符串来设置它吗?
是的,你可以使用反射 - 只要用Type.GetProperty
(必要时指定绑定标志)获取它,然后适当地调用SetValue
。示例:
using System;
class Person
{
public string Name { get; set; }
}
class Test
{
static void Main(string[] arg)
{
Person p = new Person();
var property = typeof(Person).GetProperty("Name");
property.SetValue(p, "Jon", null);
Console.WriteLine(p.Name); // Jon
}
}
如果它不是一个公共属性,则需要在GetProperty
调用指定BindingFlags.NonPublic | BindingFlags.Instance
。
下面是我的测试片段写在C#.NET
using System;
using System.Reflection;
namespace app
{
class Tre
{
public int Field1 = 0;
public int Prop1 {get;set;}
public void Add()
{
this.Prop1+=this.Field1;
}
}
class Program
{
static void Main(string[] args)
{
Tre o = new Tre();
Console.WriteLine("The type is: {0}", o.GetType()); //app.Tre
Type tp = Type.GetType("app.Tre");
object obj = Activator.CreateInstance(tp);
FieldInfo fi = tp.GetField("Field1");
fi.SetValue(obj, 2);
PropertyInfo pi = tp.GetProperty("Prop1");
pi.SetValue(obj, 4);
MethodInfo mi = tp.GetMethod("Add");
mi.Invoke(obj, null);
Console.WriteLine("Field1: {0}", fi.GetValue(obj)); // 2
Console.WriteLine("Prop1: {0}", pi.GetValue(obj)); // 4 + 2 = 6
Console.ReadLine();
}
}
}
它是一个静态属性? – BoltClock
我会将问题重命名为:“是否可以使用反射来设置属性的值?”答案是:是的,这是可能的。你能行的。 –
@Snowbear它不允许我在标题中使用问题,并且需要15个字符。如果你不喜欢标题,那么改变它。 – user489041