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

后端 未结 5 1511
情歌与酒
情歌与酒 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.

    0 讨论(0)
  • 2021-01-02 12:37

    Maybe implementing a non-generic EqualTo, which takes an Object as the argument type, would solve the issue of rewriting those code lines.

    0 讨论(0)
  • 2021-01-02 12:44

    Since you can't do exactly what you are wanting to do, how about defining an EqualTo(object) overloaded method? That should allow your required syntax.

    0 讨论(0)
  • 2021-01-02 12:55

    Not possible without explicitly specifying a T or doing a cast. Generics are compile time constructs and as such if the compiler can't figure out the type at compile time, then it won't compile (as you're seeing).

    0 讨论(0)
  • 2021-01-02 13:03

    Consider the following method:

    public bool IsNullString<T>(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<string>(null);
    bool second = IsNullString<Foo>(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<object>(null)
    

    or define an overload

    private static Matcher<object> EqualTo(object item) {
        return new IsEqual<object>(item);
    }
    
    0 讨论(0)
提交回复
热议问题