其中t:类泛型约束和const值声明

Mar*_*zek 5 c# generics const

根据C#规范10.4 Constants:

常量声明中指定的类型必须是 sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal,bool,string,enum-type 或reference-type.每个常量表达式必须生成目标类型或可通过隐式转换(第6.1节)转换为目标类型的类型的值.

为什么我不能做以下事情:

public class GenericClass<T>
    where T : class
{
    public const T val = null;
}
Run Code Online (Sandbox Code Playgroud)

这应该是可能的,因为:

  • where T : class意思是,The type argument must be a reference type; this applies also to any class, interface, delegate, or array type(来自MSDN)
  • 它满足规范中的另一个单词:除了stringis 之外的引用类型常量的唯一可能值null.

任何可能的解释?

Mar*_*zek 0

Eric Lippert承认这是一个错误,应该允许它:

\n\n
\n

在我看来,你\xe2\x80\x99发现了一个错误;要么错误在规范中,应该明确指出类型参数不是有效类型,要么错误在编译器中,应该允许它。

\n
\n