Default method parameters in C#

时间秒杀一切 提交于 2019-12-19 05:24:18

问题


How can I make a method have default values for parameters?


回答1:


A simple solution is to overload the method:

private void Foo(int length)
{
}

private void Foo()
{
    Foo(20);
}



回答2:


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:

  • The parameterless constructor of a value type
  • default(T) for some type T

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.

This (and other new features in C# 4) are covered in the second edition of C# in Depth. (Chapter 13 in this case.)




回答3:


C# 4.0 allows you to use named and optional arguments:

public void ExampleMethod(
    int required, 
    string optionalstr = "default string",
    int optionalint = 10
)

In previous versions you could simulate default parameters by using method overloading.




回答4:


You simply declare them with the default values - they are called optional parameters:

 public void myMethod(string param1 = "default", int param2 = 3)
 {
 }

This was introduced in C# 4.0 (so you will need to use visual studio 2010).



来源:https://stackoverflow.com/questions/3482528/default-method-parameters-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!