【发布时间】:2013-07-22 23:35:01
【问题描述】:
根据10.4 Constants中的C#规范:
常量声明中指定的类型必须是 sbyte, byte, 短,ushort,int,uint,long,ulong,char,float,double,decimal, bool、string、枚举类型、或引用类型。每个 常量表达式必须产生目标类型或类型的值 可以通过隐式转换转换为目标类型 (§6.1)。
为什么我不能做以下事情:
public class GenericClass<T>
where T : class
{
public const T val = null;
}
这应该是可能的,因为:
-
where T : class表示The type argument must be a reference type; this applies also to any class, interface, delegate, or array type(来自MSDN) - 它满足规范中的另一个词:
string以外的引用类型常量的唯一可能值是null。
有什么可能的解释吗?
【问题讨论】:
-
T本身就是规范所称的泛型类型参数,而不是引用类型。 -
这毫无意义。你为什么不把
const改成static? -
另外,你到底为什么要这么做?
-
@SLaks 但
where不是将T限制为类引用类型吗?