3

I've got a generic class, which contains a value. This class stores a default value and I want to check, whether the stored value equals to the default one.

At first, I tried simply:

public bool IsDefault
{
    get
    {
        return value == defaultValue;
    }
}

But unfortunately (and surprisingly) that does not compile - compiler complains, that it cannot compare T to T. The second approach is:

public bool IsDefault
{
    get
    {
        if (value == null)
            return defaultValue == null;
        else
            return value.Equals(defaultValue);
    }
}

It works, but I have a problem with strings, because a null string in my case equals to empty string, but the previous code does not cover that.

I may specialize the class for strings, but I'd avoid that if it is not necessary. Is there a way to compare two T's in a generic way?


Edit: in response to comments

Let's assume, that the class looks like the following:

public class MyClass<T>
{
    private T value;
    private T defaultValue;

    public MyClass(T newDefault)
    {
        value = newDefault;
        defaultValue = newDefault;
    }

    public T Value
    {
        get
        {
            return value;
        }
        set
        {
            this.value = value;
        }
    }

    public bool IsDefault
    {
        get
        {
            // ?
        }
    }
}
4

1 回答 1

4

您的类的构造函数应该将 aIEqualityComparer<T>作为参数,并且重载可以传入EqualityComparer<T>.Default. 存储它并用于测试是否相等。在字符串的情况下,传入IEqualityComparer<string>考虑"" == null.

像这样:

class Example<T>
{
    private readonly IEqualityComparer<T> comparer;
    private readonly T defaultValue;
    private T value;

    public Example(T value, T defaultValue, IEqualityComparer<T> comparer)
    {
        this.value = value;
        this.defaultValue = defaultValue;
        this.comparer = comparer;
    }

    public Example(T value, T defaultValue)
        : this(value, defaultValue, EqualityComparer<T>.Default)
    {
    }

    public Example(T value)
        : this(value, default(T))
    {
    }

    public Example()
        : this (default(T))
    {
    }

    public bool IsDefault
    {
        get
        {
            if (value == null)
            {
                return defaultValue == null;
            }
            else
            {
                return comparer.Equals(value, defaultValue);
            }
        }
    }
}
于 2013-11-08T08:24:01.443 回答