Dot-Net
type 和 nullable<type> 的擴展方法
為簡單起見,假設我想為 int 類型編寫一個擴展方法?和詮釋:
public static class IntExtentions { public static int AddOne(this int? number) { var dummy = 0; if (number != null) dummy = (int)number; return dummy.AddOne(); } public static int AddOne(this int number) { return number + 1; } }這可以僅使用一種方法來完成嗎?
不幸的是沒有。你可以使int?(或您使用的任何可空類型)方法很容易呼叫不可空方法,因此您不需要使用 2 種方法複製任何邏輯 - 例如
public static class IntExtensions { public static int AddOne(this int? number) { return (number ?? 0).AddOne(); } public static int AddOne(this int number) { return number + 1; } }
你不能。這可以通過編譯以下程式碼進行實驗驗證
public static class Example { public static int Test(this int? source) { return 42; } public void Main() { int v1 = 42; v1.Test(); // Does not compile } }如果您希望在兩種類型上都使用它,則需要為每種類型(可空和不可空)編寫擴展方法。