即使参数没有null约束,也会收到有关可为null的类型参数的错误 [英] Receiving error about nullable type parameter even when parameter has notnull constraint
问题描述
我有一个通用接口IDataAdapter<T>
;接口的实现者应该能够从数据源中读取具有Guid
ID的POCO. IDataAdapter<T>
有一个方法Read(Guid id)
,我想返回一个T?
,其中null表示在数据源中未找到匹配项.但是,即使在IDataAdapter<T>
上具有约束T : notnull
,尝试定义此方法也会出现错误CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
,即使在T
约束为notnull
的情况下,为什么我仍然会收到此错误?
I have a generic interface IDataAdapter<T>
; implementors of the interface should be able to read POCOs with Guid
IDs from a data source. IDataAdapter<T>
has a method Read(Guid id)
which I want to return a T?
, where null indicates that no matches were found in the data source. However, even with a constraint T : notnull
on IDataAdapter<T>
, attempting to define this method gives the error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
Why am I still getting this error, even with T
constrained to notnull
?
代码(应在带有<Nullable>enable</Nullable>
的C#8环境中):
Code (should be in a C# 8 environment with <Nullable>enable</Nullable>
):
interface IDataAdapter<T> where T : notnull
{
T? Read (Guid id); // error CS8627
}
推荐答案
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<T>
.
因此,让我们考虑一下您的方法:
So let's consider your method:
T? Read (Guid id);
在CLR中应如何表示?什么是退货类型?编译器不知道T
是引用类型还是值类型,因此编译器无法确定方法签名应为:
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);
或:
Nullable<T> Read (Guid id);
这篇关于即使参数没有null约束,也会收到有关可为null的类型参数的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!