[英]How can I add a default value for a string array in a method?
我有一個將string[]
作為參數的方法,但我無法為其提供默認值:
void Foo(string[] param = new[]) {
}
抱怨默認值應該是編譯時間常數。 但是空數組的編譯時間常數是多少?
我知道我可以使用default
,但我想知道語法是什么,如果可能的話。
默認值必須是編譯時值,並且 C# 中沒有編譯時常量 arrays,您的選項是:
default
將意味着null
所以你必須將string[]
更改為string[]?
.
void Foo(string[]? x = default) // OK.
{
}
void Foo(string[] x = default) // Cannot convert null literal to non-nullable reference type.
{
}
為了減輕打擊,您可以:
void Foo(string[]? x = default)
{
string[] y = x ?? new string[] {};
// use y below
}
甚至:
void Foo() => Foo(new string[] {});
void Foo(string[] a)
{
}
您可以使用帶有params 關鍵字的可選參數,它允許您將可變數字 arguments 傳遞給該方法。
你可以參考這個頁面。 https://geeksnewslab.com/how-to-add-a-default-value-for-a-string-array-in-a-method/
默認值必須是C#中的以下之一:
常量表達式;
new ValType() 形式的表達式,其中 ValType 是值類型,例如枚舉或結構;
default(ValType) 形式的表達式,其中 ValType 是值類型。”
您創建的 arrays 不遵循上述 C# 的任何規則,它是a reference type so there can be only one default value which is:
null
還有一件事,Array 是一個引用類型,所以它由new
關鍵字初始化,所以任何由 new 初始化的東西都不能是常量,因此引用類型的常量是null
所以你可以使用= null or = default
void Foo(string[] param = null) {
param = param==null ? new[] : param;
}
或者
void Foo(string[] param = default) {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.