传递微观的< t>进行比较

发布于 2025-01-25 12:17:53 字数 435 浏览 3 评论 0原文

我有以下代码:

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.icomable'不能分配给参数类型't?'

如何避免此错误?

I have a following code:

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?'
    }
}

Argument type 'System.IComparable' is not assignable to parameter type 'T?'

How can I avoid this error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

玩物 2025-02-01 12:17:53

在课程级别上添加通用约束,以确保t实现iComable&lt; t&gt;。然后用Just T在属性和参数类型中替换iComparable&lt; t&gt;

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

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

Add a generic constraint at the class level to ensure that T implements IComparable<T>. Then replace IComparable<T> in the property and parameter type with just T.

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

    public int foo(T b)
    {
        return a.CompareTo(b);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文