new一个泛型的实例,编译失败了,为什么?

TEDSpeak 2014-10-22 04:32:05
几行非常简单的代码:

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
public class My<T>
{
public T Create()
{
return new T();
}
}
}
}

结果提示编译错误:
error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
这是为什么呢? 泛型本身就是不论类型,都能创建啊
...全文
574 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
相思梦 2014-10-23
  • 打赏
  • 举报
回复
class List<T> : where T : new() { public T gcnewT { get{ return new T(); } } }
smthgdin_020 2014-10-23
  • 打赏
  • 举报
回复
在类的声明后面价格约束,where T:new() 因为方法create里需要new T 所以,T必须要有个无参数的构造函数。
jetable 2014-10-23
  • 打赏
  • 举报
回复
程序员不懂英文就麻烦了,错误提示已经很清楚了,可能你不知道泛型约束的东西吧
我现在在路上 2014-10-23
  • 打赏
  • 举报
回复
new ().....让编译器知道这个T泛型是有无参数的构造函数的,因为你new T()了
  • 打赏
  • 举报
回复
Cannot create an instance of the variable type 'T' because it does not have the new() constraint => because 'T' does not have the new() constraint
sunny906 2014-10-22
  • 打赏
  • 举报
回复
引用 楼主 TEDSpeak 的回复:
结果提示编译错误: error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
异常提示已经很明显地告诉你应该怎么做了,少了约束where T : new()
小汽车 2014-10-22
  • 打赏
  • 举报
回复
相当于加了一个限制条件。这样才能保证T有new可以被调用。
Forty2 2014-10-22
  • 打赏
  • 举报
回复
因为不是所有的类型都有公开的无参构造函数的。你要告诉编译起T可以用new T(): public class My<T> where T : new() { ...
bdmh 2014-10-22
  • 打赏
  • 举报
回复

        public class My<T> where T: new()
        {
            public T Create()
            {
                return new T();
            }
        }

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧