繁体   English   中英

传递 IComparable 时出错<t>比较对象</t>

[英]Error while passing IComparable<T> to CompareTo

我有以下代码:

public class Foo<T>
{
    private IComparable<T> a { get; set; }
    
    public int foo(IComparable<T> b)
    {
        return a.CompareTo(b); // compile error : Argument type 'System.IComparable<T>' is not assignable to parameter type 'T?'
    }
}

参数类型“System.IComparable”不能分配给参数类型“T?”

我怎样才能避免这个错误?

在 class 级别添加通用约束以确保T实现IComparable<T> 然后将属性和参数类型中的IComparable<T>替换为T

public class Foo<T> where T : IComparable<T>
{
    private T a { get; set; }

    public int foo(T b)
    {
        return a.CompareTo(b);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM