[英]Use “Optional, DefaultParameterValue” attribute, or not?
使用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");
它們編譯相同,編譯器可以正常工作。 唯一的區別是缺少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
是唯一改變的東西。
不同之處在於,通過顯式使用屬性,編譯器不會對類型要求強制執行相同的嚴格性。
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) { }
}
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中查看此類內容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.