Csharp/C#教程:反思和generics类型分享


反思和generics类型

我正在为类构造函数编写一些代码,它循环遍历类的所有属性,并调用一个通用的静态方法,该方法使用外部API中的数据填充我的类。 所以我把它作为一个示例类:

public class MyClass{ public string Property1 { get; set; } public int Property2 { get; set; } public bool Property3 { get; set; } public static T DoStuff(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]); } } 

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

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

你想用T =每个属性的类型调用DoStuff 吗? 在这种情况下,“按原样”你需要使用reflection和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); } 

但是,这不是很漂亮。 实际上,我想知道如果不是更好的话:

 static object DoStuff(string name, Type propertyType); ... and then object value = DoStuff(p.Name, p.PropertyType); 

在这个例子中,generics给你的是什么? 请注意,在reflection调用期间,值类型仍会被装箱等 – 甚至拳击也没有您想象的那么糟糕 。

最后,在许多场景中,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]); } } 

? 注意DoStuff而不是MyClass

如果是这样,那么问题在于,当他们真的不适用时,你会尝试使用generics。 generics(嗯,其中一点)的用途是使用编译时类型安全性。 这里你不知道编译时的类型! 您可以通过reflection调用该方法(获取打开的表单,然后调用MakeGenericMethod ),但这非常难看。

DoStuff真的需要首先是通用的吗? 它是从其他地方使用的吗? PropertyInfo.SetValue的参数只是对象,所以即使你可以通常调用方法,你仍然会得到拳击等。

如果您不从其他地方使用DoStuff,我还建议您编写非generics方法。

也许您创建了通用方法以便能够使用默认值(T)。 要在非generics方法中替换它,可以对值类型使用Activator.CreateInstance(T),对引用类型使用null:

上述就是C#学习教程:反思和generics类型分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 object defaultResult = type.IsValueType ? Activator.CreateInstance(type) : null 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1011676.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐