gpt4 book ai didi

c# - 创建参数化通用对象的实例,并将所有参数设置为 null

转载 作者:太空狗 更新时间:2023-10-30 00:30:59 24 4
gpt4 key购买 nike

假设一个带有参数化构造函数的类:

MyObject(string param1, string param2, string param2)
{
...
}

我有一个 Generic 方法,它返回 Generic Class 的一个实例,并且MyObject 就是其中之一。

How can I instantiate a generic class with a parameterized constructor and pass null values to all its parameters? This is needed as properties of the generic class get populated at a slightly later stage.

我尝试使用 Activator 作为:

public static T GetGenericObject<T>()
{
T resource = (T)Activator.CreateInstance(typeof(T), null);
...
}

但我得到异常,我在 MyObject 中没有无参数构造函数。我知道我可以很容易地添加一个,但是不能修改类(不要问为什么)。

最佳答案

您可以通过反射检测有多少参数,然后在 Activator.CreateInstance() 中为每个参数传入空值:

var parameters = typeof(T)
.GetConstructors()
.Single()
.GetParameters()
.Select(p => (object)null)
.ToArray();
T resource = (T)Activator.CreateInstance(typeof(T), parameters);

请注意,这假定只有一个构造函数,并且它只适用于引用类型,因此它相当脆弱。

关于c# - 创建参数化通用对象的实例,并将所有参数设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348525/

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