C# 创建对象 obj = new T()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11234452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:04:19  来源:igfitidea点击:

C# create Object obj = new T()?

c#generics

提问by sehlstrom

I have a superclass we can call class Aand few subclasses, e.g. class a1 : A, class a2 : A, ... and a6 : A. In my class B, I have a set of methods that creates and adds one of the subclasses to a List<A>in B.

我有一个我们可以调用的超类class A和几个子类,例如class a1 : A, class a2 : A, ... 和a6 : A。在 my 中class B,我有一组方法可以创建一个子类并将其添加到List<A>in 中B

I want to shorten my code I have at the moment. So instead of writing

我想缩短我目前的代码。所以而不是写作

Adda1()
{
    aList.Add( new a1() );
}

Adda2()
{
    aList.Add( new a2() );
} 

...

Adda6()
{
    aList.Add( new a6() );
}

Instead I want to write something similar to this

相反,我想写一些类似的东西

Add<T>()
{
    aList.Add( new T() );  // This gives an error saying there is no class T.
}

Is that possible?

那可能吗?

Is it also possible to constraint that Thas to be of type Aor one of its subclasses?

是否也可以约束T必须是类型A或其子类之一?

采纳答案by Mark Byers

Lee's answer is correct.

李的回答是正确的。

The reason is that in order to be able to call new T()you need to add a new()constraint to your type parameter:

原因是为了能够调用new T()您需要new()向您的类型参数添加一个约束:

void Add<T>() where T : new()
{
     ... new T() ...
}

You also need a constraint T : Aso that you can add your object of type Tto a List<A>.

您还需要一个约束,T : A以便您可以将类型的对象添加TList<A>.

Note: When you use new()together with other contraints, the new()constraint must come last.

注意:new()与其他new()约束一起使用时,约束必须放在最后

Related

有关的

回答by Lee

public void Add<T>() where T : A, new()
{
    aList.Add(new T());
}