C#创建对象obj =新T()? [英] C# create Object obj = new T()?

查看:263
本文介绍了C#创建对象obj =新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.
}

是否有可能?



也可以约束 T 必须是 A 或其某个子类?

解决方案

Lee的答案是正确的。

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

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

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



注意:当您使用 new() 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆