【发布时间】:2008-10-13 07:37:22
【问题描述】:
我正在为类构造函数编写一些代码,该构造函数循环遍历类的所有属性并调用通用静态方法,该方法使用来自外部 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]);
}
}
所以上面的构造函数会抛出一个错误,因为我没有提供泛型类型。
那么我该如何传入属性的类型呢?
【问题讨论】:
-
对不起,这个问题有点混乱,第二个代码 sn-p 有错别字吗?
-
是的,我想你的意思是写“MyClass.DoStuff(p.Name)”作为 p.SetValue() 的第二个参数。
-
是的,我在第二个代码 sn-p 中犯了一个错误。
标签: c# .net generics reflection