我正在爲類構造函數編寫一些代碼,它循環遍歷類的所有屬性,並調用一個通用的靜態方法,它使用來自外部API的數據填充我的類。所以我有這個作爲一個例子類:反射和泛型類型
public class MyClass{
public string Property1 { get; set; }
public int Property2 { get; set; }
public bool Property3 { get; set; }
public static T DoStuff<T>(string name){
// get the data for the property from the external API
// or if there's a problem return 'default(T)'
}
}
現在在我的構造函數我想是這樣的:
public MyClass(){
var properties = this.GetType().GetProperties();
foreach(PropertyInfo p in properties){
p.SetValue(this, DoStuff(p.Name), new object[0]);
}
}
所以上面的構造函數將拋出一個錯誤,因爲我不供應泛型類型。
那麼如何傳遞屬性的類型呢?
對不起的問題是怎麼樣的混亂,有沒有第二個代碼的一些錯字片段? – smaclell 2008-10-13 07:44:21