How to allow a generic type parameter for a C# method to accept a null argument?

后端 未结 5 1510
情歌与酒
情歌与酒 2021-01-02 11:57
private static Matcher EqualTo(T item)
{
    return new IsEqual(item);
}

How do I modify the above method definition suc

5条回答
  •  清酒与你
    2021-01-02 13:03

    Consider the following method:

    public bool IsNullString(T item) {
        return typeof(T) == typeof(string) && item == null;
    }
    

    Yes, this is a pathetically stupid method and using generics is pointless here, but you'll see the point in a moment.

    Now consider

    bool first = IsNullString(null);
    bool second = IsNullString(null);
    
    bool third = IsNullString(null);
    

    In the first and second, the compiler can clearly distinguish the type of T (no inference is needed). In the third, how the compiler infer what T is? In particular, it can't distinguish between T == string and T == Foo, or any other type for that matter. Therefore, the compiler has to give you a compile-time error.

    If you want to get around this, you either need to cast null

    EqualTo((object)null);
    

    or explicitly state the type

    EqualTo(null)
    
    
    

    or define an overload

    private static Matcher EqualTo(object item) {
        return new IsEqual(item);
    }
    
        

    提交回复
    热议问题