有沒有辦法將空參數傳遞給C#方法(類似於C++中的空參數)?將空參數傳遞給C#方法
例如:
是否可以翻譯下面的C++函數到C#方法:
private void Example(int* arg1, int* arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
有沒有辦法將空參數傳遞給C#方法(類似於C++中的空參數)?將空參數傳遞給C#方法
例如:
是否可以翻譯下面的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的包裝器。這使您可以封裝不可爲空的值類型幷包含空值信息。
雖然使用情況稍有不同。
// 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.
}
從C#2.0:
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
您可以使用NullableValueTypes(如int? ) 爲了這。該代碼會是這樣:
private void Example(int? arg1, int? arg2)
{
if(!arg1.HasValue)
{
//do something
}
if(!arg2.HasValue)
{
//do something else
}
}
從C#2.0開始,您可以使用可空的泛型類型可空,並在C#中有一個速記符號後面的類型?
例如
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
我認爲C#相當於最接近int*
會ref int?
。因爲ref int?
允許被調用的方法將值傳遞迴調用方法。
int*
ref int?
的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
您可以使用2種方式:int?或Nullable,都具有相同的行爲。你可以在沒有問題的情況下進行混音,但是使代碼變得最乾淨是更好的選擇。
選項1(帶):
private void Example(int? arg1, int? arg2)
{
if (arg1.HasValue)
{
//do something
}
if (arg1.HasValue)
{
//do something else
}
}
選項2(可空):
private void Example(Nullable<int> arg1, Nullable<int> arg2)
{
if (arg1.HasValue)
{
//do something
}
if (arg1.HasValue)
{
//do something else
}
}
從C#4.0提供了一個新的方式做同樣的更大的靈活性,在這如果框架提供optional parameters with default values,這樣,如果不帶所有參數調用該方法,則可以設置默認值。
選項3(使用默認值)
private void Example(int arg1 = 0, int arg2 = 1)
{
//do something else
}
能不能請你告訴我的差值B/W'私人無效例(INT?ARG1)`和`私人無效例(INT?ARG1 = 0)` – Unbreakable 2017-10-30 20:05:45