相关疑难解决方法(0)

反思和泛型类型

我正在为类构造函数编写一些代码,它循环遍历类的所有属性,并调用一个通用的静态方法,该方法使用外部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)'
  }
}
Run Code Online (Sandbox Code Playgroud)

现在在我的构造函数中我想要这样的东西:

public MyClass(){
  var properties = this.GetType().GetProperties();
  foreach(PropertyInfo p in properties){
    p.SetValue(this, DoStuff(p.Name), new object[0]);
  }
}
Run Code Online (Sandbox Code Playgroud)

所以上面的构造函数会抛出一个错误,因为我没有提供泛型类型.

那么如何传入属性的类型呢?

.net c# generics reflection

12
推荐指数
2
解决办法
2万
查看次数

标签 统计

.net ×1

c# ×1

generics ×1

reflection ×1