繁体   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