加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 课堂上的约束

发布时间:2020-12-15 23:49:54 所属栏目:百科 来源:网络整理
导读:试图在类上定义约束,但得到错误: public class Utilities3T where T : IComparable{ public T MaxT(T a,T b) { return a.CompareTo(b) 0 ? a : b; }} ‘T’ does not contain a definition for ‘CompareTo’ and no extension method ‘CompareTo’ accept
试图在类上定义约束,但得到错误:

public class Utilities3<T> where T : IComparable
{
    public T Max<T>(T a,T b) 
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

‘T’ does not contain a definition for ‘CompareTo’ and no extension method ‘CompareTo’ accepting a first argument of type ‘T’ could be found (are you missing a using directive or an assembly reference?)

Cannot resolve symbol ‘CompareTo’

error

虽然对函数的约束很好:

public class Utilities2<T>
{
    public T Max<T>(T a,T b) where T : IComparable
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

为什么限制课不工作?

解决方法

这行代码:

public T Max<T>(T a,T b)

定义一个新的< T>覆盖用于该类的约束.删除此< T>在方法中,您将使用类约束

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读