一个模版的编译错误,大家帮我看看吧

adavcds 2014-03-06 09:39:21

interface IMy<T>
{
T f();
}
class s<T> : IMy<T>
{
public T f() { return new T(); }
}

编译报错: error CS0304: Cannot create an instance of the variable type 'T' because it does not have the new() constraint
这个应该怎么改呢?
...全文
154 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
adavcds 2014-03-07
  • 打赏
  • 举报
回复
引用 6 楼 wanghui0380 的回复:
interface IMy<T> where T :class, new() { T f(); }
这个约束条件不能作用于不能实例化的"接口"之上,"约束(constraining)类型,可以限制可用于实例化泛型类的类型"。因此4楼说的是对的。
wanghui0380 2014-03-06
  • 打赏
  • 举报
回复
interface IMy<T> where T :class, new() { T f(); }
threenewbee 2014-03-06
  • 打赏
  • 举报
回复
这不叫“模板”,这叫泛型。C#和C++是不同的。
本拉灯 2014-03-06
  • 打赏
  • 举报
回复


 interface IMy<T>
    {
        T f();
    }


    class S<T> : IMy<T> where T : new()
    {
        public T f() { return new T(); }

    }
要这样才对 不要写要接口上
adavcds 2014-03-06
  • 打赏
  • 举报
回复
引用 1 楼 wanghui0380 的回复:
interface IMy<T> where T:new() { T f(); }
光这样改还不行:

        interface IMy<T> where T : new()
        {
            T f();
        }
        class s<T> : IMy<T>
        {
            public T f() { return new T(); }
        }
现在的编译错误是: error CS0310: 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'ConsoleApplication1.Program.IMy<T>' 我现在还需要怎么改呢?
wanghui0380 2014-03-06
  • 打赏
  • 举报
回复
interface IMy<T> where T:new() { T f(); }

110,534

社区成员

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

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

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