【问题标题】:Nullable Method Arguments in C# [duplicate]C# 中的可空方法参数 [重复]
【发布时间】:2010-10-12 21:47:29
【问题描述】:

重复问题

Passing null arguments to C# methods

我可以在 c# 中为 .Net 2.0 执行此操作吗?

public void myMethod(string astring, int? anint)
{
//some code in which I may have an int to work with
//or I may not...
}

如果没有,我可以做类似的事情吗?

【问题讨论】:

  • 我进行了搜索,但没有出现重复的内容,或者可以回答这个问题。谢谢大家。

标签: c# arguments nullable


【解决方案1】:

是的,假设您是故意添加人字形并且您的真正意思是:

public void myMethod(string astring, int? anint)

anint 现在将具有 HasValue 属性。

【讨论】:

    【解决方案2】:

    取决于你想要达到的目标。如果您希望能够删除anint 参数,则必须创建一个重载:

    public void myMethod(string astring, int anint)
    {
    }
    
    public void myMethod(string astring)
    {
        myMethod(astring, 0); // or some other default value for anint
    }
    

    您现在可以这样做:

    myMethod("boo"); // equivalent to myMethod("boo", 0);
    myMethod("boo", 12);
    

    如果您想传递一个可为空的 int,那么,请参阅其他答案。 ;)

    【讨论】:

    • +1 使用多态性的好建议
    • @Garry,是的,你的权利不是。
    • 我认为您可以通过如下定义避免过载:public void myMethod(string astring, int? anint = null)。这样,您只能使用字符串作为参数调用该方法,并且 anint 变量的值将为空;并用字符串和整数调用它。
    【解决方案3】:

    在 C# 2.0 中你可以这样做;

    public void myMethod(string astring, int? anint)
    {
       //some code in which I may have an int to work with
       //or I may not...
    }
    

    然后像这样调用方法

     myMethod("Hello", 3);
     myMethod("Hello", null);
    

    【讨论】:

      猜你喜欢
      • 2020-01-21
      • 2015-07-19
      • 2011-03-19
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      相关资源
      最近更新 更多