我如何新T()? [英] How do I new T()?
本文介绍了我如何新T()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想这样做:
公共类myclass< T>
{
myclass()
{}
public void CreateNew()
{
T myp = new T( );
}
}
但是,我得到这个编译错误:
无法创建变量类型''T'的实例,因为它没有
有new()约束
我可以将类输入为Person。这意味着我想在调用CreateNew时创建一个新的
Person对象。有办法吗?
谢谢,
布雷特
I''d like to do this:
public class myclass<T>
{
myclass()
{}
public void CreateNew()
{
T myp = new T();
}
}
However, I get this compiler error:
Cannot create an instance of the variable type ''T'' because it does not
have the new() constraint
I may type the class as Person. This means I want to create a new
Person object when CreateNew is called. Is there a way to do this?
Thanks,
Brett
推荐答案
使用
T myp = default(T);
参见:
http://msdn2.microsoft.com/en-us /lib...0d(vs.80).aspx
Use
T myp = default(T);
See also:
http://msdn2.microsoft.com/en-us/lib...0d(vs.80).aspx
Ahhg!谢谢。
Brett
Ahhg! Thank you.
Brett
我认为这不可行,但是有没有办法得到通用的
我可以做:
// contructor
public Collection(int personId)
{
T p =默认(T)(personId);
this.Add(p.PersonId,p);
}
因此,我的T型提前知道它可能正在处理什么。我或者
也可能有e.employeeId的员工类型或者带有
c.customerId的客户类型。代码可以转到:
public Collection(int entityId)
{
T e = default(T)(entityId );
this.Add(e.?Id,p);
}
我知道T不会提前知道但是还有另一种方法可以实现类似的做法。我不想处理每个特定的
案例或使用开关和条件来检查类型。
谢谢,
Brett
I don''t think this is possible but is there a way to get generic enough
that I can do:
//contructor
public Collection ( int personId )
{
T p = default(T) ( personId );
this.Add ( p.PersonId, p );
}
So that my type T knows ahead of time what it may be dealing with. I
may also have Employee types with e.employeeId or Customer types with
c.customerId. The code may go to:
public Collection ( int entityId )
{
T e = default(T) ( entityId );
this.Add ( e.?Id, p );
}
I know T doesn''t know ahead of time but is there another way to go
about doing it similar to that. I don''t want to handle each specific
case or use switches and conditionals to check the type.
Thanks,
Brett
这篇关于我如何新T()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文