Aar*_*ell 12 .net c# generics reflection
我正在为类构造函数编写一些代码,它循环遍历类的所有属性,并调用一个通用的静态方法,该方法使用外部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)
所以上面的构造函数会抛出一个错误,因为我没有提供泛型类型.
那么如何传入属性的类型呢?
Mar*_*ell 19
你想用T =每个属性的类型调用DoStuff <T>吗?在这种情况下,"按原样"你需要使用反射和MakeGenericMethod - 即
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);
}
Run Code Online (Sandbox Code Playgroud)
但是,这不是很漂亮.实际上,我想知道如果不是更好的话:
static object DoStuff(string name, Type propertyType);
... and then
object value = DoStuff(p.Name, p.PropertyType);
Run Code Online (Sandbox Code Playgroud)
在这个例子中,泛型给你带来了什么?请注意,在反射调用期间,值类型仍然会被装箱等 - 甚至拳击也没有您想象的那么糟糕.
最后,在许多场景中,TypeDescriptor.GetProperties()比Type.GetProperties()更合适 - 允许灵活的对象模型等.
您的构造函数代码是否意味着如下所示:
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)
?请注意DoStuff而不是MyClass.
如果是这样,那么问题在于,当它们真的不适用时,你会尝试使用泛型.泛型(点,其中一点)的要点是使用编译时类型安全性.这里你不知道编译时的类型!您可以通过反射调用该方法(获取打开的表单,然后调用MakeGenericMethod)),但这非常难看.
首先DoStuff真的需要通用吗?它是从其他地方使用的吗?参数to PropertyInfo.SetValue只是对象,所以你仍然可以获得拳击等,即使你可以通常调用该方法.
| 归档时间: |
|
| 查看次数: |
16734 次 |
| 最近记录: |