gpt4 book ai didi

c# - 使用非空构造函数初始化泛型

转载 作者:行者123 更新时间:2023-11-30 20:17:16 25 4
gpt4 key购买 nike

引用那个问题:Cannot create an instance of the variable type 'Item' because it does not have the new() constraint

我想从具有非空构造函数的泛型类型创建一个实例。

public class A{};

public class B
{
public B(int){/*...*/}
}

public class C
{
public static T validate<T>(int index)
where T : A,
new(int) //error
{
if(/*validation*/)
return null;
return new T(index);
}
}

如果我尝试调用 B b = validate<B>(42);我收到此错误:

'B' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'C.validate(int)'

问题 1:为什么我只能使用无参数构造函数?

问题 2:如何在没有委托(delegate)或接口(interface)的情况下解决我的问题?(我一直在寻找奇特的解决方案。)

最佳答案

C# 11 更新

static abstract/virtual members in interfaces功能,设计时考虑了通用数学,但可用于为您的类型要求静态工厂函数,非常适合,如果您可以更改类型实现,我建议使用它。

只需添加一个 static abstract T Create(your params come here...) 到一个接口(interface),然后以 T : IYourInterface 的形式添加一个约束到你的方法。

然后,只需使用T.Create(...) 来创建一个实例。太棒了,不是吗?!


旧答案

您可以使用反射来调用构造函数:

var constructorInfo = typeof(T).GetConstructor(new[] { typeof(int) });
if (constructorInfo != null)
{
object[] parameters = new object[] { index };
return (T)constructorInfo.Invoke(parameters);
}
else
{
// handle it
}

(改编自https://stackoverflow.com/a/13523659/5962841)


或者,您可以使用激活器创建一个实例(参见@datrax 的回答)

(T)Activator.CreateInstance(typeof(T), index)

您要求的功能已经经常被要求。

正在此处跟踪对该功能的请求 (github csharp design repo),但不要指望今年,它甚至没有原型(prototype)或被接受。

关于c# - 使用非空构造函数初始化泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45370334/

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