簡體   English   中英

可選的非系統類型參數

[英]Optional non-system type parameters

C#4.0帶來了可選參數,我已經等了很長時間了。 但是,似乎因為只有System類型可以是const ,所以我不能使用我創建的任何類/結構作為可選參數。

有沒有一種方法可以讓我使用更復雜的類型作為可選參數。 或者這是人們必須忍受的現實之一?

我能想出的最佳參考類型是:

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);
}

您可以使用任何類型作為可選參數:

using System;

class Bar { }

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

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

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

不幸的是,這是不允許的,因為必須在編譯時知道默認參數的值,以便編譯器可以將其烘焙到程序集中。

暫無
暫無

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

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