[英]Optional non-system type parameters
C#4.0 brings optional parameters, which I've been waiting for for quite some time. C#4.0带来了可选参数,我已经等了很长时间了。 However it seems that because only System types can be const
, I cannot use any class/struct which I have created as an optional parameter. 但是,似乎因为只有System类型可以是const
,所以我不能使用我创建的任何类/结构作为可选参数。
Is there a some way which allows me to use a more complex type as an optional parameter. 有没有一种方法可以让我使用更复杂的类型作为可选参数。 Or is this one of the realities that one must just live with? 或者这是人们必须忍受的现实之一?
The best I could come up with for reference types was: 我能想出的最佳参考类型是:
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));
}
}
You can use the same idea for structs by making the parameter nullable: 您可以通过使参数为可为空来对结构使用相同的想法:
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);
}
You can use any type as an optional parameter: 您可以使用任何类型作为可选参数:
using System;
class Bar { }
class Program
{
static void Main()
{
foo();
}
static void foo(Bar bar = null) { }
}
Okay, I reread your question and I think I see what you mean - you want to be able to do something like this: 好的,我重读了你的问题,我想我明白了你的意思 - 你希望能够做到这样的事情:
static void foo(Bar bar = new Bar()) { }
Unfortunately this is a not allowed since the value of the default parameter must be known at compile time so that the compiler can bake it into the assembly. 不幸的是,这是不允许的,因为必须在编译时知道默认参数的值,以便编译器可以将其烘焙到程序集中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.