如何声明通用值类型的const字段作为通配参数提供 [英] How to declare a const field of a generic value type provided as generic argument
问题描述
我正在尝试定义一个通用类,接受作为参数的值类型(实际上它将是一个枚举),并使用其默认类型初始化一个const字段。
I'm trying to define a generic class that accept as argument a value type (actually it will be an enum) and initialize a const field with it's default type.
我想要的东西:
public abstract class GenericClass<ValueType>
where ValueType: struct, IConvertible
{
public const ValueType val = default(ValueType);
}
不幸的是编译器投诉(我使用的是Mono,但我认为是一样的在网上)。错误如下:
Unfortunately the compiler complaints (I'm using Mono but I think it's the same on .NET). The error is the following:
错误CS1959:类型参数`ValueType'不能声明const
error CS1959: Type parameter `ValueType' cannot be declared const
我的错误是什么?
推荐答案
类型参数不允许用于常量类型
Type parameter is not allowed for constant type.
因为 struct
不能生成 const
从 C#规范10.4常量)
常量声明中指定的类型必须为
sbyte
,byte
,short
,ushort
,int
,uint
,long
code> ulong ,char
,float
,double
,decimal
,bool
,string
,枚举类型或引用类型。
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.
此限制的一种解决方法是将其声明为 static
readonly
。
A kind of workaround to this limitation is to declare it as static
readonly
.
public static readonly ValueType val = default(ValueType);
这篇关于如何声明通用值类型的const字段作为通配参数提供的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!