2010-12-20 25 views
10

如何編寫一個可以將Nullable對象用作擴展方法的泛型方法。我想添加一個XElement到一個父元素,但只有當要使用​​的值不爲null時。爲空的<T> C#中的泛型方法?

例如

public static XElement AddOptionalElement<T>(this XElement parentElement, string childname, T childValue){ 
... 
code to check if value is null 
add element to parent here if not null 
... 
} 

如果我使這AddOptionalElement<T?>(...)然後我得到編譯器錯誤。 如果我使這AddOptionalElement<Nullable<T>>(...)然後我得到編譯器錯誤。

有沒有一種方法可以實現這個目標?

我知道我可以讓我的調用方法:

parent.AddOptionalElement<MyType?>(...) 

但是這是唯一的辦法?

回答

12
public static XElement AddOptionalElement<T>(
    this XElement parentElement, string childname, T? childValue) 
    where T : struct 
{ 
    // ... 
} 
+0

類型「T」必須是一個非空值類型,以便用它作爲參數「T」在通用類型或方法「System.Nullable 」 – BlueChippy 2010-12-20 11:00:43

+0

它仍然會有編譯器錯誤,因爲我們需要指出T需要是不可空的。 – 2010-12-20 11:01:45

+0

@BlueChippy:正如您評論的那樣正在解決這個問題! – LukeH 2010-12-20 11:02:06

4

需要約束T是一個struct - 否則它不能爲空。

public static XElement AddOptionalElement<T>(this XElement parentElement, 
              string childname, 
              T? childValue) where T: struct { ... } 
+0

它不是需要可以爲空的「this」,而是其他參數之一。例如方法名稱(此XElement父級,「NeedANullableHere」值) – BlueChippy 2010-12-20 11:02:10

+0

編輯...您的「拿Nullable對象用作擴展方法」有點混淆。 – Lucero 2010-12-20 11:06:32

1

嘗試
AddOptionalElement<T>(T? param) where T: struct { ... }

0

The Nullable類型具有約束where T : struct, new()所以你的方法obviuosly應包含struct約束,使Nullable<T>工作的罰款。將得到的方法應該是這樣的:

public static XElement AddOptionalElement<T>(this XElement parentElement, string childname, T? childValue) where T : struct 
    { 
     // TODO: your implementation here 
    } 
+2

'struct'意味着'new()'作爲約束,不需要明確地添加它。 – Lucero 2010-12-20 11:07:55

+1

已修復,謝謝你的提示。 – 2010-12-20 11:19:02