C#默认参数
示例
如果要提供省略参数的选项,则可以使用默认参数:
static void SaySomething(string what = "ehh") {
Console.WriteLine(what);
}
static void Main() {
// prints "hello"
SaySomething("hello");
// prints "ehh"
SaySomething(); // The compiler compiles this as if we had typed SaySomething("ehh")
}当您调用此类方法并忽略为其提供默认值的参数时,编译器将为您插入该默认值。
请记住,具有默认值的参数需要在没有默认值的参数之后编写。
static void SaySomething(string say, string what = "ehh") {
//Correct
Console.WriteLine(say + what);
}
static void SaySomethingElse(string what = "ehh", string say) {
//Incorrect
Console.WriteLine(say + what);
}警告:因为它可以那样工作,所以默认值在某些情况下可能会出现问题。如果更改方法参数的默认值并且不重新编译该方法的所有调用程序,则这些调用程序仍将使用编译时存在的默认值,这可能会导致不一致。
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练