默认方法的参数在C# [英] Default method parameters In C#
问题描述
我怎样才能使该方法有一个参数的缺省值?
How i can make the method have a default values for parameters ?
推荐答案
您只能做这在C#4,介绍双方的命名参数和可选参数的:
You can only do this in C# 4, which introduced both named arguments and optional parameters:
public void Foo(int x = 10)
{
Console.WriteLine(x);
}
...
Foo(); // Prints 10
请注意,默认值必须是恒定的 - 无论是正常的编译时间常数(如文字),或者:
Note that the default value has to be a constant - either a normal compile-time constant (e.g. a literal) or:
- 值类型的参数的构造函数
-
默认(T)
对某些类型的T
- The parameterless constructor of a value type
default(T)
for some typeT
另外还要注意,默认值是嵌入在主叫方的的组件(假设你忽略了相关参数) - 如果你更改默认值,无需重建调用code,你会仍然可以看到旧值。
Also note that the default value is embedded in the caller's assembly (assuming you omit the relevant argument) - so if you change the default value without rebuilding the calling code, you'll still see the old value.
这(和C#4等新功能)覆盖在 C#在深度第二版。 (第13章在此情况下)。
This (and other new features in C# 4) are covered in the second edition of C# in Depth. (Chapter 13 in this case.)
这篇关于默认方法的参数在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!