我正在为类构造函数编写一些代码,它循环遍历类的所有属性,并调用一个通用的静态方法,它使用来自外部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