将空参数传递给C#方法

Nik*_*lin 29 c# methods null

有没有办法将空参数传递给C#方法(类似于c ++中的空参数)?

例如:

是否可以将以下c ++函数转换为C#方法:

private void Example(int* arg1, int* arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}
Run Code Online (Sandbox Code Playgroud)

San*_*der 73

是..NET中有两种类型:引用类型和值类型.

引用类型(通常是类)总是通过引用引用,因此它们支持null而无需任何额外的工作.这意味着如果变量的类型是引用类型,则该变量自动成为引用.

默认情况下,值类型(例如int)没有null的概念.但是,有一个名为Nullable的包装器.这使您可以封装非可空值类型并包含空信息.

但用法略有不同.

// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
    if (arg1.HasValue)
        DoSomething();

    arg1 = null; // Valid.
    arg1 = 123;  // Also valid.

    DoSomethingWithInt(arg1); // NOT valid!
    DoSomethingWithInt(arg1.Value); // Valid.
}
Run Code Online (Sandbox Code Playgroud)


mac*_*nir 7

我认为最近的C#相当于int*ref int?.因为ref int?允许被调用的方法将值传递回调用方法.

int*

  • 可以为null.
  • 可以是非null并指向整数值.
  • 如果不为null,则可以更改值,并且更改将传播到调用方.
  • 设置为null不会传递回调用者.

ref int?

  • 可以为null.
  • 可以有一个整数值.
  • 可以始终更改值,并将更改传播给调用方.
  • 值可以设置为null,此更改也将传播给调用者.


Mar*_*n K 5

从 C# 2.0 开始:

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}
Run Code Online (Sandbox Code Playgroud)


MAD*_*Map 5

你可以使用NullableValueTypes(比如int?).代码如下:

private void Example(int? arg1, int? arg2)
{
    if(!arg1.HasValue)
    {
        //do something
    }
    if(!arg2.HasValue)
    {
        //do something else
    }
}
Run Code Online (Sandbox Code Playgroud)