Receiving error about nullable type parameter even when parameter has notnull constraint

前端 未结 3 448
既然无缘
既然无缘 2021-01-18 14:13

I have a generic interface IDataAdapter; implementors of the interface should be able to read POCOs with Guid IDs from a data source.

3条回答
  •  粉色の甜心
    2021-01-18 15:06

    I think this issue is very similar to what is happening in this post.

    Note that a T? where T : class and a T? where T : struct are represented very differently in the CLR. The former is just the CLR type T. There are not separate types in the CLR to differentiate between T and T?. T? in C# just adds extra compile time checking by the C# compiler. On the other hand, The latter is represented by the CLR type Nullable.

    So let's consider your method:

    T? Read (Guid id);
    

    How should this be represented in the CLR? What is the return type? The compiler don't know whether T is a reference type or a value type, so the compiler cannot decide whether the method signature should be:

    T Read (Guid id);
    

    or:

    Nullable Read (Guid id);
    

提交回复
热议问题