2010-04-21 45 views
6

C#4.0帶來了可選參數,我一直在等待一段時間。不過看起來,因爲只有系統類型可以是const,所以我不能使用我創建的任何類/結構作爲可選參數。可選的非系統類型參數

是否有某種方式允許我使用更復雜的類型作爲可選參數。或者,這是人們必須忍受的現實之一嗎?

+0

是沒有限定爲「系統類型「。什麼使你相信? – 2010-04-21 01:10:58

+0

他們可以是其他類型,但唯一可用的默認值爲空(或可能是類型可以隱式轉換的東西,但我不能測試這個,因爲我沒有4.0在工作)) – 2010-04-21 01:41:02

回答

10

我能想出的引用類型的最好的是:

using System; 

public class Gizmo 
{ 
    public int Foo { set; get; } 
    public double Bar { set; get; } 

    public Gizmo(int f, double b) 
    { 
     Foo = f; 
     Bar = b; 
    } 
} 

class Demo 
{ 
    static void ShowGizmo(Gizmo g = null) 
    { 
     Gizmo gg = g ?? new Gizmo(12, 34.56); 
     Console.WriteLine("Gizmo: Foo = {0}; Bar = {1}", gg.Foo, gg.Bar); 
    } 

    public static void Main() 
    { 
     ShowGizmo(); 
     ShowGizmo(new Gizmo(7, 8.90)); 
    } 
} 

您可以通過參數爲空的使用相同的想法結構:

public struct Whatsit 
{ 
    public int Foo { set; get; } 
    public double Bar { set; get; } 

    public Whatsit(int f, double b) : this() 
    { 
     Foo = f; Bar = b; 
    } 
} 

static void ShowWhatsit(Whatsit? s = null) 
{ 
    Whatsit ss = s ?? new Whatsit(1, 2.3); 
    Console.WriteLine("Whatsit: Foo = {0}; Bar = {1}", 
     ss.Foo, ss.Bar); 
} 
+0

我一直在思考這些問題,但是因爲我使用的是一個結構,所以它也不那麼喜歡。不知道爲什麼我沒有讓func採用可空的版本(Size?size = null)。 – 2010-04-21 01:45:14

+0

System.Nullable ...現在我記得我在結構中有一個額外的「初始化」字段的想法。 :) FY: – 2010-04-21 01:49:08

+1

,你仍然可以使用?具有可空結構的運算符。 – 2010-04-21 10:11:53

6

你可以使用任何類型的可選參數:

using System; 

class Bar { } 

class Program 
{ 
    static void Main() 
    { 
     foo(); 
    } 
    static void foo(Bar bar = null) { } 
} 

好吧,我重讀你的問題,我想我明白你的意思 - 你希望能夠做這樣的事情:

static void foo(Bar bar = new Bar()) { } 

不幸的是,這是不允許的,因爲在編譯時必須知道默認參數的值,以便編譯器可以將它燒入程序集。

+0

「烘烤到程序集「 - 人們忽略了更改庫中參數的默認值不會在未重新編譯的客戶端代碼中更改它的事實。 – 2015-12-11 13:23:39