简体   繁体   English

某种int的C#方法参数是否可以接受null并可以更新参数

[英]Is it possible that a C# method parameter of some kind of int can accept null and can update argument

As below code expressed, I want SomeMethod 如下面的代码所示,我想要SomeMethod

  • Have a parameter of some kind of int 具有某种int的参数
  • can accept null as parameter 可以接受null作为参数
  • if parameter is none null, it will use it's value, then update the value of argument variable in Caller2 如果parameter不为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 } } 

Tried and declare: 尝试并声明:

  • ref int can't accept null ref int不能接受null
  • int? 诠释? can't update argument in caller 无法更新调用方中的参数
  • Create a custom Wrapper class of int did this, but is there a light way or does C# or .net have some build in tech? 创建一个自定义int的Wrapper类可以做到这一点,但是有没有简单的方法,或者C#或.net在技术上有一些内建?
  • It's not good to split it into two methods because there's a big logic inside which is common whenever parameter is null or none null. 将其分为两个方法不是很好,因为其中有一个很大的逻辑,每当参数为null或none为null时,逻辑就很常见。

Almost there, you can use int? 快到了,可以使用int? to allow null value and put the ref keyword. 以允许为空值放置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;
    }
}

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

相关问题 如何允许C#方法的通用类型参数接受空参数? - How to allow a generic type parameter for a C# method to accept a null argument? 为什么枚举参数不能在重载方法中接受int值(> 0) - Why the enum parameter can NOT accept the int value(>0) in overload method 如何在C#中将任何类型的数字作为参数接受到函数中? - How to accept any kind of number into a function as an argument in C#? 我可以接受 c# 中的一个参数的多种类型吗? - Can i accept multiple types for one parameter in c#? 可以从表达式参数推断其类型参数的 C# 通用方法 - C# Generic method that can infer its type argument from expression parameter C#泛型如何获取没有对象类型作为参数的泛型方法的参数类型? - C# Generics How Can I get the type passed as an argument for a generic method with no object type as a parameter? 我们可以将 C# 委托作为方法参数传递吗? 如果是这样如何传递一个论点? - Can we pass C# delegate as a method parameter? If so how to pass an argument? 我们可以在 C# 8.0 中避免使用不可为空的方法参数的空参数保护子句吗? - Can we avoid null argument guard clauses with non-nullable method parameters in C# 8.0? 限制泛型子类方法在c#中可以接受的类型 - Restrict types a generic subclass method can accept in c# C#可以锁定方法参数吗? - C# can I lock a method parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM