c# 2.0中可空值的默认值
本文关键字:空值 默认值 | 更新日期: 2023-09-27 18:15:23
使用c# 2.0,我可以像这样指定一个默认参数值:
static void Test([DefaultParameterValueAttribute(null)] String x) {}
由于c# 4.0语法不可用:
static void Test(String x = null) {}
那么,c# 2.0是否有等价的值类型呢?例如:
static void Test(int? x = null) {}
下面的尝试不能编译。
// error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type
static void Test([DefaultParameterValueAttribute(null)] int? x) {}
// error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression
static void Test([DefaultParameterValueAttribute(new Nullable<int>())] int? x) {}
遗憾的是,旧版本的c#编译器不支持此功能。
c# 4.0编译器编译这个:
public static void Foo(int? value = null)
为:
public static void Foo([Optional, DefaultParameterValue(null)] int? value)
这实际上与您的第一次尝试(另外添加了OptionalAttribute
)相同,c# 2编译器在CS1908中错误,因为该版本的编译器不直接支持。
如果你需要支持c# 2,在这种情况下,我建议添加一个重载方法:
static void Test()
{
Test(null);
}
static void Test(int? x)
{
// ..
Reed当然是正确的;我只是想加一个关于极端情况的有趣事实。在c# 4.0中,你可以说:(对于结构类型S)
void M1(S x = default(S)) {}
void M2(S? x = null) {}
void M3(S? x = default(S?)) {}
但是奇怪的是你不能说
void M4(S? x = default(S)) {}
在前三种情况下,我们可以简单地发出元数据,表示"可选值是形式参数类型的默认值"。但在第四种情况下,可选值是不同类型的默认值。没有一种明显的方法可以将这种事实编码到元数据中。我们没有在不同语言间制定一致的规则来编码这样的事实,而是简单地在c#中将其定为非法。这可能是一个罕见的角落案例,所以没有太大的损失。
显然你不能使用这个属性。
正如你所知道的,属性参数在编译时被"序列化"到元数据-所以你需要常量表达式。因为编译器不喜欢'null',所以你没有选择了。
你可以重载定义另一个没有参数的Text方法,用null
这个工作:[DefaultParameterValueAttribute((int?)null)]
吗?(
我认为应该是:
static void Text(int? x = default(int?));