5
給出一個基本的類定義:如何使用反射動態設置對象實例屬性的值?
using System.Reflection;
public class Car()
{
public int speed {get;set;}
public void setSpeed()
{
Type type = this.GetType();
PropertyInfo property = type.GetProperty(PropertyName);
property.SetValue(type, Convert.ToInt32(PropertyValue), null);
}
}
此代碼示例被簡化,而不是使用動態類型轉換,我只想要一個工作示例設置的實例屬性。
編輯:上面代碼中的PropertyName和PropertyValue也被簡化了。
在此先感謝
你當前的代碼得到什麼問題嗎? –
@CuongLe它試圖設置一個屬性類型爲'Car'的屬性值爲'System.Type'類型的實例,這將不起作用 –