是否使用"Optional,DefaultParameterValue"属性?

Kor*_*ray 24 c# optional-parameters c#-4.0

使用OptionalDefaultParameterValue属性之间是否有任何区别而不使用它们?

public void Test1([Optional, DefaultParameterValue("param1")] string p1, [Optional, DefaultParameterValue("param2")] string p2)
{
}

public void Test2(string p1= "param1", string p2= "param2")
{
}
Run Code Online (Sandbox Code Playgroud)

两者都有效:

Test1(p2: "aaa");
Test2(p2: "aaa");
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 18

它们编译相同,编译器可以正常工作.唯一的区别是缺乏using System.Runtime.InteropServices;,更容易阅读代码.

作为参考,IL是:

.method public hidebysig instance void TheName([opt] string p1,
    [opt] string p2) cil managed
{
    .param [1] = string('param1')
    .param [2] = string('param2')
    .maxstack 8
    L_0000: ret 
}
Run Code Online (Sandbox Code Playgroud)

TheName唯一改变的地方在哪里.


小智 9

不同之处在于,通过显式使用属性,编译器不会对类型要求强制执行相同的严格性.

public class C {
  // accepted
  public void f([Optional, DefaultParameterValue(1)] object i) { }

  // error CS1763: 'i' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null
  //public void g(object i = 1) { }

  // works, calls f(1)
  public void h() { f(); }
}
Run Code Online (Sandbox Code Playgroud)

请注意,即使使用DefaultParameterValue,也不会丢弃类型安全性:如果类型不兼容,则仍会标记此类型.

public class C {
  // error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
  //public void f([Optional, DefaultParameterValue("abc")] int i) { }
}
Run Code Online (Sandbox Code Playgroud)