C#4.0 带来了可选参数,我已经等待了很长时间。但是似乎因为只有系统类型可以const
,所以我不能使用我创建的任何类/结构作为可选参数。
有什么方法可以让我使用更复杂的类型作为可选参数。或者这是人们必须忍受的现实之一?
C#4.0 带来了可选参数,我已经等待了很长时间。但是似乎因为只有系统类型可以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()) { }
不幸的是,这是不允许的,因为默认参数的值必须在编译时知道,以便编译器可以将其烘焙到程序集中。