我知道我的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