2012-10-26 43 views
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也被簡化了。

在此先感謝

+0

你當前的代碼得到什麼問題嗎? –

+0

@CuongLe它試圖設置一個屬性類型爲'Car'的屬性值爲'System.Type'類型的實例,這將不起作用 –

回答

7

傳遞應該是實例保存你要設置的屬性的第一個參數。如果它是一個靜態屬性,則爲第一個參數傳遞null。根據你的情況修改代碼:

public void setSpeed() 
    { 
     Type type = this.GetType(); 
     PropertyInfo property = type.GetProperty(PropertyName); 
     property.SetValue(this, Convert.ToInt32(PropertyValue), null); 
    } 

一個天真的類型轉換,你可以做

var value = Convert.ChangeType(PropertyValue,property.PropertyType); 
    property.SetValue(this, value, null); 
+0

是的 - 這就像一個魅力! –

相關問題