簡體   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語法不可用:

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)
{
    // ..

里德當然是正確的; 我只是想我會在一個角落案例中添加一個有趣的事實。 在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調用Text方法

這是否有效: [DefaultParameterValueAttribute((int?)null)] 試過 - 這也行不通(

我相信它應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM