2017-03-06 68 views
1

如下面的代码表示,我想的someMethod有没有可能是某种为int的C#方法参数可以接受空和可更新参数

  • 有某种的参数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 
        } 
    } 
    
更新参数变量的值

尝试并宣布:

  • 裁判INT不能接受空
  • 诠释?无法更新呼叫者
  • 参数创建一个自定义包装类int的这样做,但有一个光路或做C#或.net在一些高科技打造?
  • ,因为有一个大的逻辑中是常见的,只要参数为空或返回null这不是很好的将它分为两​​种方法。
+2

为什么你不在你的方法中使用返回值? – Jehof

+1

'ref int?'怎么样? – dotctor

+0

@ Jehof,谢谢,int?参数和返回值一起解决我的问题 – zhiyazw

回答

2

快到了,你可以用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; 
    } 
} 
+0

谢谢,ref int?能做到这一点,但它不接受字面的someMethod(NULL,..),它需要像这样调用:INT? unused = null; SomeMethod(引用未使用)。在我个人的情况下,我更喜欢Jehof的解决方案。不管怎样,谢谢你。 – zhiyazw

相关问题