泛型类等于约束输入参数和对象具有相同类型 T 的方法

本文关键字:对象 同类型 方法 参数 于约束 约束 输入 泛型类 | 更新日期: 2023-09-27 18:33:59

以下 [c#] 代码不会编译,并显示错误"运算符 == 不能应用于类型'T'和'T'的操作数"。

public class Widget<T> where T: IComparable
{
    public T value;
    public Widget(T input) { value = input; }
    public bool Equals<T>(Widget<T> w) where T : System.IComparable
    {
        return (w.value == value);
    }
}

有没有办法将w输入参数的类型T约束为与要比较的对象相同的T类型,从而保证它们可以相互比较并消除编译器错误? 在下面的值前面使用(动态)可以编译,但似乎有更好的方法可以在编译时捕获问题:

public bool Equals<T>(Widget<T> w) where T : System.IComparable { return (w.value == (dynamic) value); }

泛型类等于约束输入参数和对象具有相同类型 T 的方法

假设你真的对这里的值相等感兴趣,你可以只使用EqualityComparer.Default

EqualityComparer<T> comparer = EqualityComparer<T>.Default;
return comparer.Equals(w.value, value);

请注意,当前您的Equals方法也是泛型的,尝试声明另一个类型参数 T。我不认为你真的想那样做。

这是你想要的吗?

public class Widget<T> : IEquatable<Widget<T>>, IComparable<Widget<T>>
    where T : IEquatable<T>, IComparable<T>
{
    public T value;
    public Widget(T input) { value=input; }
    public override bool Equals(object obj)
    {
        if(obj is Widget<T>)
        {
            return Equals(obj as Widget<T>);
        }
        return false;
    }
    public override int GetHashCode()
    {
        return value.GetHashCode();
    }
    public bool Equals(Widget<T> other)
    {
        return value.Equals(other.value);
    }
    public int CompareTo(Widget<T> other)
    {
        return value.CompareTo(other.value);
    }
    public static bool operator==(Widget<T> a, Widget<T> b)
    {
        return a.Equals(b);
    }
    public static bool operator!=(Widget<T> a, Widget<T> b)
    {
        return !a.Equals(b);
    }
    public static bool operator<(Widget<T> a, Widget<T> b)
    {
        return a.CompareTo(b)==-1;
    }
    public static bool operator>(Widget<T> a, Widget<T> b)
    {
        return a.CompareTo(b)==1;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Widget<int> a=new Widget<int>(100);
        Widget<int> b=new Widget<int>(200);
        if(a==b||a>b)
        {
        }
    }
}
public class Widget<T> where T: IComparable
{
    public T value;
    public Widget(T input) { value = input; }
    public bool Equals(Widget<T> other)
    {
        if(value == null)
        {
          return other == null || other.Value == null;
        }
        if(other == null) return false; //ensure next line doesn't get null pointer exception
        return value.CompareTo(other.Value) == 0;
    }
}

可能需要根据你希望它如何对待空检查逻辑来对待valueotherother.value为空的各种排列。

public class Widget<T> where T: IEquatable<T>
{
    public T value;
    public Widget(T input) { value = input; }
    public bool Equals(Widget<T> w)
    {
        return (w.value.Equals(this.value));
    }
}

如果需要相等比较,则应使用 IEquatableIComparable更适合当您还需要顺序比较(小于、大于)时。

我认为您的主要错误是您在Equals<T>方法中引入了一个新的类型参数。不要;相反,让 Widget<T> 参数中的T与实例化类的类型相同。这保证了w.Valuethis.value的类型相同。