Document directory
- Before C #4.0
- After 4.0:
- The story behind
- References:
In C #4.0, what attracts me first is the default parameter. When I use this feature very smoothly in Python, C # can only write a large number of overload functions, and then call one function, and finally call the one with the most parameters.
Before C #4.0
Before 4.0, When I want a function parameter to have a default value, it must be written as follows:
static void OldFun(string param1){ OldFun(param1, "default param2");}static void OldFun(string param1, string param2){ OldFun(param1, param2, "default param3");}static void OldFun(string param1, string param2, string param3){ var content = string.Format("{0},{1},{2}",param1,param2,param3); Console.WriteLine(content);}
I am so miserable that I cannot understand why Microsoft does not provide a default parameter. I envy C ++ programmers.
After 4.0:
In C #4.0, Microsoft finally added this feature.
The new Code is much simpler.
static void Main(string[] args){ OldFun("GreenerycnDemo"); OldFun("GreenerycnDemo", "abc"); OldFun("greenerycn", "cnblogs", "com");}static void OldFun( string param1, string param2 = "default param2", string param3 = "default param3"){ var content = string.Format("{0},{1},{2}", param1, param2, param3); Console.WriteLine(content);}
After execution:
Note: parameters with default values must be placed at the end of the parameter list, that is, the following method cannot be used; otherwise, the compilation will fail.
static void OldFun(string param2 = "default param2", string param1, string param3 = "default param3"){ var content = string.Format("{0},{1},{2}",param1,param2,param3); Console.WriteLine(content);}
Compilation failed:
The story behind
What did Microsoft do with such a convenient feature? Let's take a look at it with reflector:
private static void OldFun(string param1, [Optional, DefaultParameterValue("default param2")] string param2, [Optional, DefaultParameterValue("default param3")] string param3){ Console.WriteLine(string.Format("{0},{1},{2}", param1, param2, param3));}
Haha, we added the optional and defaultparametervalue attributes to the parameter signature.
These two attributes are in the namespace system. runtime. interopservices:
- Optionalattribute: this parameter is optional.
- Defaultparametervalueattribute: the default value of this attribute setting parameter.
According to some materials: According to this principle, the optional parameters mentioned above must be followed by the code to specify these two attributes, so that the compilation will be okay. However, I cannot do it myself. An error will still be reported during the call.
How can this problem be solved? I will tell you in the next article.
References:
- New features in C # 4.0.doc
- C #4.0-named and optional parameters-behind the scenes
- C #4.0 features: named & optional parameters (optional and named parameters)