Reflection and generic types

后端 未结 3 1486
借酒劲吻你
借酒劲吻你 2020-12-05 05:48

I\'m writing some code for a class constructor which loops through all the properties of the class and calls a generic static method which populates my class with data from

3条回答
  •  臣服心动
    2020-12-05 06:23

    Was your constructor code meant to read like this:

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

    ? Note the DoStuff instead of MyClass.

    If so, the problem is that you're trying to use generics when they're really not applicable. The point of generics (well, one of the points) is to use compile-time type safety. Here you don't know the type at compile time! You could call the method by reflection (fetching the open form and then calling MakeGenericMethod) but that's pretty ugly.

    Does DoStuff really need to be generic in the first place? Is it being used from elsewhere? The parameter to PropertyInfo.SetValue is just object, so you'd still get boxing etc even if you could call the method generically.

提交回复
热议问题