English 中文(简体)
c# 2.0
原标题:Default value for nullable value in c# 2.0

采用C# 2.0,我可以具体说明一种缺省参数价值,如:

static void Test([DefaultParameterValueAttribute(null)] String x) {}

自此C# 4.0 syntax

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)

Into:

public static void Foo([Optional, DefaultParameterValue(null)] int? value)

这实际上与你第一次尝试(此外还有<代码>OptionalAttribute)相同,C# 2汇编者与CS1908的错误一样,因为该表是汇编者直接支持的。

如果你需要支持第2号C,我建议增加超负荷的方法:

static void Test()
{
    Test(null);
}
static void Test(int? x)
{
    // ..
问题回答

Reed is of course correct; I just thought I d add an interesting fact about a corner case. In C# 4.0 you can say: (for struct type S)

void M1(S x = default(S)) {}
void M2(S? x = null) {}
void M3(S? x = default(S?)) {}

But oddly enough you cannot say

void M4(S? x = default(S)) {}

在头3起案件中,我们可以简单地提供元数据,指出“任择值是正式参数类型违约值”。 但就第四而言,选择价值是不同类型<>的缺省值。 将这种事实编码为元数据并无明显的方法。 我们不是在各种语文中制定一条统一规则,说明这种事实,而是在C#中将其定为非法。 这可能是一个罕见的玉米案例,因此没有重大损失。

Apparently you can t use this attribute.

如你所知,属性参数在汇编时被编成元数据,因此,你需要不断表达。 由于编辑者不喜欢放弃选择。

你们可以做的是——超载——界定另一个 案文方法,无任何参数,可称为案文方法,无效

Does this work: [DefaultParameterValueAttribute((int?)null)]? Tried - this doesn t work too (

我认为应该:

static void Text(int? x = default(int?));




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签