如何使用类作为泛型

时间:2014-06-22 17:42:18

标签: c# generics

我有一个班级

public class Customer
{
    ...
}

我也有一种使用泛型的方法:

public static T Show<T>(DependencyObject sender, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) where T : IComparable<T>, new()
{
    ...
}

现在,当我想在我的程序中调用它时:

Customer customerSelect = NoruBox.Show<Customer>(this, MessageBoxIcon.Box, "GridBox test", customerData, Noru.Controls.MessageBoxButton.SelectCancel);

我确实得到了一个错误。它表示类型Customer不能用作T中的类型参数Show<T>(...)。没有从CustomerSystem.IComparable<Customer>的隐式引用转换。


我尝试public class Customer : IComparable并将以下内容添加到Class

public int CompareTo(object obj)
{
    var other = obj as Customer;
    if (other == null) return 0;
    return CompareTo(other);
}

但这没有任何区别。

2 个答案:

答案 0 :(得分:1)

约束要求IComparable<Customer>,而不是IComparable

public class Customer : IComparable<Customer> {

  public int CompareTo(Customer other) {
    ...
  }

  ...
}

答案 1 :(得分:1)

您想要比较每个Customer实例的哪个方面?在下面的示例中,我假设A包含键值。

public class Customer : IComparable<Customer>
{
    public int CompareTo(Customer other)
    {
        if (other == null) return 1;
        return this.A.CompareTo(other.A);
    }
}
相关问题