C#使用Missing.Value与仅从方法调用中忽略可选参数之间的区别? [英] C# Difference between using Missing.Value and just leaving out the optional parameter from method call?

查看:409
本文介绍了C#使用Missing.Value与仅从方法调用中忽略可选参数之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在广泛搜索之后,我发现了很多有关Missing.Value将默认值传递给可选参数的内容的信息.

So, after extensively searching, I found a lot of information about what the Missing.Value does passing the default value to an optional parameter.

但是在某种程度上,没有一个提及它为什么有用的提示,而不是仅将可选参数全部省略,在这种情况下,它也得到了它的默认值.

But somehow not a single mention about why is it more useful, than just leaving out the optional parameter alltogether in which case, it also gets it's default value.

在Office女士互操作代码示例中使用它,但尝试将其忽略,并且可以正常工作,正如所期望的那样,那么,有什么用呢?

Came across it in a Ms Office interop code sample, but tried leaving it out, and works all the same, just as excpected, so, what gives?

例如在:

oWB = oXL.Workbooks.Add( Missing.Value );

vs

oWB = oExcel.Workbooks.Add();

推荐答案

仅使用不同的示例来阐明Optional/Named参数的好处,因为已经共享了oWB = oXL.Workbooks.Add( Missing.Value );.

Just to clarify benifit of Optional/Named parameters with different example because oWB = oXL.Workbooks.Add( Missing.Value ); is already shared.

缺失值

(来自备注)例如,当您调用具有默认参数值的方法时,请使用Missing类的此实例表示缺失值.

(From Remarks) Use this instance of the Missing class to represent missing values, for example, when you invoke methods that have default parameter values.

来自缺少类

    public class MissingClass
    {
        public static void MethodWithDefault(int value = 33)
        {
            Console.WriteLine("value = {0}", value);
        } 
    }

public class Example
{
   public static void Main()
   {
      // Invoke without reflection
      MissingClass.MethodWithDefault();

      // Invoke by using reflection.
      Type t = typeof(MissingClass);
      MethodInfo mi = t.GetMethod("MethodWithDefault");
      mi.Invoke(null, new object[] { Missing.Value });
   }
}
// The example displays the following output:
//       value = 33  
//       value = 33  

可选参数,请参见以下示例,如果此方法的调用者(GetBillingInfo)没有为这些参数提供值,则将使用提供给参数的默认值

Optional Parameter, See following example ,if caller of this method(GetBillingInfo) does not supply values for those parameters then the default value provided to the parameters will be used

您将可以通过4种方式调用您的方法

You will be able to call your method by 4 ways

GetBillingInfo();//No parametes (kValue,quoteID)
GetBillingInfo("kvalue"); // KValue
GetBillingInfo("KValue" , 20); // kvalue + quoteID

您可以使用paramName(命名参数)来调用它

You can call it with paramName (Named Parameters)

GetBillingInfo(quoteID: 20) //quoteID

阅读 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆