C#创建对象obj =新T()? [英] C# create Object obj = new T()?
问题描述
我有一个超类,我们可以调用 class A
和很少的子类, class a1:A
, class a2:A
,...和 a6:A
。在我的 class B
中,我有一组方法创建并添加一个子类到 List< A>
in B
。
我想缩短我目前的代码。因此,不要写
Adda1()
{
aList.Add(new a1());
}
Adda2()
{
aList.Add(new a2());
}
...
Adda6()
{
aList.Add(new a6());
$ / code>
相反,我想写一些与此类似的东西。
Add< T>()
{
aList.Add(new T()); //这个错误提示没有类T.
}
是否有可能?
也可以约束 A
或其某个子类?
Lee的答案是正确的。
原因是为了能够调用 new T()
,您需要添加一个 new()
约束到你的类型参数:
void Add< T>()其中T:new()
{
... new T()...
}
您还需要一个约束 T:A
,以便您可以将类型 T
的对象添加到 List< A>
。
注意:当您使用
new()$ c $与其他限制一起, new()
约束必须来自 last 。
相关
I have a superclass we can call class A
and 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
.
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 T
has to be of type A
or one of its subclasses?
解决方案 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:
void Add<T>() where T : new()
{
... new T() ...
}
You also need a constraint T : A
so that you can add your object of type T
to a List<A>
.
Note: When you use new()
together with other contraints, the new()
constraint must come last.
Related
这篇关于C#创建对象obj =新T()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!