其中T:类通用的限制和const声明价值 [英] where t : class generic constraint and const value declaration
问题描述
据 C#规格10.4常量
:
的在一个恒定的声明类型指定必须是为sbyte,字节,
短,USHORT,INT,UINT,长,ULONG,焦炭,浮点,双,十进制,
布尔,字符串,枚举型,或引用类型。每个
常量表达式必须得到目标类型或一个类型
可以通过转换为目标类型的值隐式转换
(第6.1节)
The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. Each constant-expression must yield a value of the target type or of a type that can be converted to the target type by an implicit conversion (§6.1).
那么,为什么我不能做到以下几点:
Why then I can't do following:
public class GenericClass<T>
where T : class
{
public const T val = null;
}
这应该是可能的,因为:
That should be possible, because:
-
,其中T:类
意味着,类型参数必须是引用类型;这也适用于任何类,接口,委托或数组类型
(从 MSDN ) - 它满足换句话说从规格:比
string以外的引用类型常数的唯一可能的值
是空
的
where T : class
means, thatThe type argument must be a reference type; this applies also to any class, interface, delegate, or array type
(from MSDN)- it satisfies another words from specification: the only possible value for constants of reference-types other than
string
isnull
.
任何可能的解释?
推荐答案
的埃里克利珀承认这是一个错误,它应该被允许:
Eric Lippert admitted it is a bug, and it should be allowed:
在我看来,就像你发现了一个bug;无论是bug是在规范,这应该显式调用了该类型参数无效类型,或者错误是在编译器,它应该允许它。
It looks to me like you’ve found a bug; either the bug is in the specification, which should explicitly call out that type parameters are not valid types, or the bug is in the compiler, which should allow it.
这篇关于其中T:类通用的限制和const声明价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!