C#泛型类型有一个构造函数? [英] C#: Generic types that have a constructor?
问题描述
我有下面的C#测试代码:
I have the following C# test code:
class MyItem
{
MyItem( int a ) {}
}
class MyContainer< T >
where T : MyItem, new()
{
public void CreateItem()
{
T oItem = new T( 10 );
}
}
Visual Studio中无法编译,错误的是在行,其中新的方法有:
Visual Studio can't compile it, the error is at line where 'new' is used:
'T': cannot provide arguments when creating an instance of a variable type
是否有可能在C#创建泛型类型与非参数构造函数的对象?这是没有问题,做这种事在C ++模板,所以我很好奇,为什么我不能做同样的事情在C#。也许一些额外的在那里要求或语法是不同的。
Is it possible in C# to create an object of generic type with non-parameterless constructor? It's no problem to do such thing in C++ templates, so i'm very curious why i can't do same thing in C#. Maybe some additional 'where' is required or syntax is different?
推荐答案
它可以与反思做?
public void CreateItem()
{
int constructorparm1 = 10;
T oItem = Activator.CreateInstance(typeof(T), constructorparm1) as T;
}
但是有没有通用的约束,以确保 T
实现所需的构造,所以,除非你很小心声明在每一个实现该接口类型构造我不建议这样做。
But there is no generic constraint to ensure that T
implements the desired constructor, so I wouldn't advise doing this unless you are careful to declare that constructor in every type that implements the interface.
这篇关于C#泛型类型有一个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!