简体   繁体   English

是否使用“Optional,DefaultParameterValue”属性?

[英]Use “Optional, DefaultParameterValue” attribute, or not?

Is there any difference between using Optional and DefaultParameterValue attributes and not using them? 使用OptionalDefaultParameterValue属性与不使用它们之间有什么区别吗?

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

public void Test2(string p1= "param1", string p2= "param2")
{
}

both work: 两者都有效:

Test1(p2: "aaa");
Test2(p2: "aaa");

They compile identically, and the compiler works fine with either. 它们编译相同,编译器可以正常工作。 The only difference is the lack of using System.Runtime.InteropServices; 唯一的区别是缺少using System.Runtime.InteropServices; , and easier to read code. ,更容易阅读代码。

For reference, the IL is: 作为参考,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 
}

where TheName is the only thing that changes. 其中TheName是唯一改变的东西。

The difference is that by using the attributes explicitly, the compiler doesn't enforce the same strictness on type requirements. 不同之处在于,通过显式使用属性,编译器不会对类型要求强制执行相同的严格性。

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(); }
}

Note that even with DefaultParameterValue , you don't throw out type-safety: if the types are incompatible, this will still be flagged. 请注意,即使使用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;
    }
}

They are doing the same job. 他们正在做同样的工作。 You can check things like this in Roslyn or in ReferenceSource 您可以在RoslynReferenceSource中查看此类内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM