有没有办法将空参数传递给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)
我认为最近的C#相当于int*会ref int?.因为ref int?允许被调用的方法将值传递回调用方法.
int*
ref int?
从 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)
你可以使用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)