有没有办法向 C# 方法传递空参数(类似于 c++ 中的 null 参数)?
例如:
是否可以将以下 C++ 函数转换为 C# 方法:
private void Example(int* arg1, int* arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
是的,在.NET中有两种类型:引用类型和值类型。
引用类型(通常是类)总是通过引用引用,因此它们支持null而无需任何额外的工作。这意味着如果一个变量的类型是引用类型,那么该变量自动成为引用。
值类型(例如int)默认情况下没有null的概念。但是,对于它们有一个包装器叫Nullable,可以封装不可为空的值类型并包含null信息。
然而,使用方式略有不同。
// 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.
}
int*
的是 ref int?
。因为 ref int?
允许被调用的方法将值传回到调用方法。
int*
ref int?
private void Example(int? arg1, int? arg2)
{
if(!arg1.HasValue)
{
//do something
}
if(!arg2.HasValue)
{
//do something else
}
}
从C# 2.0开始:
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
OP的问题已经得到了很好的回答,但是标题太过宽泛,我认为以下入门指南会有所帮助:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace consolePlay
{
class Program
{
static void Main(string[] args)
{
Program.test(new DateTime());
Program.test(null);
//Program.test(); // <<< Error.
// "No overload for method 'test' takes 0 arguments"
// So don't mistake nullable to be optional.
Console.WriteLine("Done. Return to quit");
Console.Read();
}
static public void test(DateTime? dteIn)
{
Console.WriteLine("#" + dteIn.ToString() + "#");
}
}
}
输出:
#1/1/0001 12:00:00 AM#
##
Done. Return to quit
从C# 2.0开始,您可以使用可空泛型类型Nullable,在C#中有一种简写方式,即在类型后面加上?
例如:
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
private void Example(int? arg1, int? arg2)
{
if (arg1.HasValue)
{
//do something
}
if (arg1.HasValue)
{
//do something else
}
}
选项二(可为空):
private void Example(Nullable<int> arg1, Nullable<int> arg2)
{
if (arg1.HasValue)
{
//do something
}
if (arg1.HasValue)
{
//do something else
}
}
private void Example(int arg1 = 0, int arg2 = 1)
{
//do something else
}
private void Example(int? arg1)
和private void Example(int? arg1 = 0)
的区别吗? - Unbreakablenull
时,并不是这种情况。你有什么想法吗? - Zimano