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

后端 未结 5 1557
情歌与酒
情歌与酒 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 12:36

    You may work around this limitation by using the following syntax:

    EqualTo("abc");
    EqualTo(4);
    EqualTo(default(object));
    //equivalently:
    EqualTo((object)null);
    

    default(T) is the value a field of type T has if not set. For reference types, it's null, for value types it's essentially memory filled with zero bytes (...which may mean different things for different types, but generally means some version of zero).

    I try to avoid the null everywhere in my code nowadays. It hampers type inference elsewhere too, such as with the var declared field and in a ternary operator. For example, myArray==null ? default(int?) : myArray.Length is OK, but myArray==null ? null : myArray.Length won't compile.

提交回复
热议问题