使用Optional
和DefaultParameterValue
属性并且不使用它们之间有什么区别吗?
public void Test1([Optional, DefaultParameterValue("param1")] string p1, [Optional, DefaultParameterValue("param2")] string p2)
{
}
public void Test2(string p1= "param1", string p2= "param2")
{
}
都工作:
Test1(p2: "aaa");
Test2(p2: "aaa");
答案 0 :(得分:17)
它们编译相同,编译器可以正常工作。唯一的区别是缺少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
}
其中TheName
是唯一改变的东西。
答案 1 :(得分: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(); }
}
请注意,即使使用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) { }
}
答案 2 :(得分:3)
namespace System.Runtime.InteropServices {
using System;
//
// The DefaultParameterValueAttribute is used in C# to set
// the default value for parameters when calling methods
// from other languages. This is particularly useful for
// methods defined in COM interop interfaces.
//
[AttributeUsageAttribute(AttributeTargets.Parameter)]
public sealed class DefaultParameterValueAttribute : System.Attribute
{
public DefaultParameterValueAttribute(object value)
{
this.value = value;
}
public object Value { get { return this.value; } }
private object value;
}
}
他们正在做同样的工作。您可以在Roslyn或ReferenceSource
中查看以下内容