反思与泛型类型 [英] Reflection and generic types
问题描述
我在写一些code的一类构造函数遍历类的所有属性和调用一个普通的静态方法,它从外部API填充我的课了数据。所以,我有这个作为一个例子类:
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 an external API. So I've got this as an example class:
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)'
}
}
现在在我的构造我想是这样的:
Now in my constructor I want something like this:
public MyClass(){
var properties = this.GetType().GetProperties();
foreach(PropertyInfo p in properties){
p.SetValue(this, DoStuff(p.Name), new object[0]);
}
}
所以上面的构造函数将抛出一个错误,因为我不提供泛型类型。
So the above constructor will thrown an error because I'm not supplying the generic type.
那么,如何通过在属性的类型?
So how do I pass in the type of the property in?
推荐答案
你想打电话DoStuff&LT; T&GT;以T =每个属性的类型?在这种情况下,原样你需要使用反射和MakeGenericMethod - 即
Do you want to call DoStuff<T> with T = the type of each property? In which case, "as is" you would need to use reflection and MakeGenericMethod - i.e.
var properties = this.GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
object value = typeof(MyClass)
.GetMethod("DoStuff")
.MakeGenericMethod(p.PropertyType)
.Invoke(null, new object[] { p.Name });
p.SetValue(this, value, null);
}
然而,这不是很pretty的。在现实中,我不知道它会不会只是为了更好地有:
However, this isn't very pretty. In reality I wonder if it wouldn't be better just to have:
static object DoStuff(string name, Type propertyType);
... and then
object value = DoStuff(p.Name, p.PropertyType);
什么是仿制药给你在这个例子吗?需要注意的是值类型仍然会得到反射通话过程中盒装等 - 而且当时拳击<一个href="http://msmvps.com/blogs/jon_skeet/archive/2008/10/08/why-boxing-doesn-t-keep-me-awake-at-nights.aspx"相对=nofollow>不是那么糟糕,因为你可能会认为。
最后,在许多情况下,TypeDescriptor.GetProperties()比Type.GetProperties()更合适。 - 允许灵活的对象模型等
Finally, in many scenarios, TypeDescriptor.GetProperties() is more appropriate than Type.GetProperties() - allows for flexible object models etc.
这篇关于反思与泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!