gpt4 book ai didi

c# - 反射和通用类型

转载 作者:可可西里 更新时间:2023-11-01 08:17:15 26 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

是否要调用 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);
}

但是,这不是很漂亮。实际上,我想知道是否只拥有:

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

在此示例中,泛型为您提供了什么?请注意,值类型在反射调用期间仍将被装箱等 - 甚至装箱 isn't as bad as you might think .

最后,在许多情况下,TypeDescriptor.GetProperties() 比 Type.GetProperties() 更合适 - 允许灵活的对象模型等。

关于c# - 反射和通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/196936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com