【问题标题】:Is it possible that a C# method parameter of some kind of int can accept null and can update argument是否有可能某种 int 的 C# 方法参数可以接受 null 并且可以更新参数
【发布时间】:2017-03-06 07:12:18
【问题描述】:

如下代码所示,我想要SomeMethod

  • 具有某种 int 的参数
  • 可以接受 null 作为参数
  • 如果参数不为空,它会使用它的值,然后更新Caller2中的参数变量的值

    void Caller1()
    {
        SomeMethod(null, ...);
    }
    
    void Caller2()
    {
        int argument = 123;
        SomeMethod(argument, ...);
        Debug.Assert(argument == 456);
    }
    
    void SomeMethod(SomeKindOfInt parameter, ...)
    {
        if (parameter != null)
        {
            // use the value of parameter;
            parameter = 456; // update the value of argument which is in Caller2
        }
    }
    

尝试并声明:

  • ref int 不能接受 null
  • int? 无法更新调用者中的参数
  • 创建一个自定义 Wrapper 类的 int 是这样做的,但是有没有简单的方法或者 C# 或 .net 有一些内置技术?
  • 把它分成两个方法是不好的,因为里面有一个很大的逻辑,当参数为空或不为空时,这是很常见的。

【问题讨论】:

  • 为什么不在方法中使用返回值?
  • ref int? 怎么样?
  • @Jehof,谢谢,int?参数和返回值一起解决我的问题
  • @dotctor,谢谢,参考 int?可以做到这一点,但它不接受文字 SomeMethod(null, ..) ,它需要这样调用: int?未使用=空; SomeMethod(参考未使用)。就我个人而言,我更喜欢 Jehof 的解决方案。还是谢谢你。

标签: c# parameters reference int nullable


【解决方案1】:

差不多了,您可以使用int? 来允许空值输入ref 关键字。

static void Main(string[] args)
{
    int? test1 = null;
    SomeMethod(ref test1);
    Console.WriteLine(test1);
    // Display 456

    int? test2 = 123;
    SomeMethod(ref test2);
    Console.WriteLine(test2);
    // Display 123

    Console.ReadLine();
}

static void SomeMethod(ref int? parameter)
{
    if (parameter == null)
    {
        parameter = 456;
    }
}

【讨论】:

  • 谢谢,参考?可以做到这一点,但它不接受文字 SomeMethod(null, ..) ,它需要这样调用: int?未使用=空; SomeMethod(参考未使用)。就我个人而言,我更喜欢 Jehof 的解决方案。还是谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-06
  • 2017-03-21
  • 2013-05-10
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 2017-09-25
相关资源
最近更新 更多