如何比较两种泛型类型?

时间:2017-11-05 08:15:26

标签: c# .net generics

我将我的类设为通用.T - 可以是字符串或int。

我有这个要素类:

public class Feature<T>// : IComparable
{
    public T CurrentFeatureCode { get; set; }

    public T StreetCode1 { get; set; }
    public T BuildingNumber1 { get; set; }
    public string BuildingLetter1 { get; set; }

    public T StreetCode2 { get; set; }
    public T BuildingNumber2 { get; set; }
    public string BuildingLetter2 { get; set; }

    public double CoordinateX { get; set; }
    public double CoordinateY { get; set; }

    public string Filter { get; set; }

    public string ToString(T streetCode)
    {
        return StreetCode2 == streetCode ? String.Format("{0}{1}", BuildingNumber2, BuildingLetter2) : String.Format("{0}{1}", BuildingNumber1, BuildingLetter1);
    }
}

正如您所看到的,我在Feature类中使用了ToString方法来比较两个值:

StreetCode2 == streetCode ? String.Format("{0}{1}", BuildingNumber2, BuildingLetter2) : String.Format("{0}{1}", BuildingNumber1, BuildingLetter1);

我在这一行收到错误:

Error   11  Operator '==' cannot be applied to operands of type 'T' and 'T' .

我的问题是如何比较T型的两个值?

3 个答案:

答案 0 :(得分:3)

对于您的类型T,请实施IEquatable<T> interface。使用适合您情况的逻辑覆盖Equals()方法。请注意,您也必须覆盖GetHashCode()

答案 1 :(得分:2)

如果您对默认比较器感到满意,那么您可以这样做:

public class Feature<T>// : IComparable
{
    public T StreetCode2 { get; set; }
    public string ToString(T streetCode)
    {
        if (EqualityComparer<T>.Default.Equals(StreetCode2, streetCode))
        {
            return "Equal";
        }

        return "Not Equal";
    }
}

这是一个测试:

var feature1 = new Feature<string>();
feature1.StreetCode2 = "two";
string equals = feature1.ToString("two");

答案 2 :(得分:1)

我认为推荐的方法是使用带有泛型和Equals()方法的IEquatable接口,但我不确定这是否符合您的口味。