好吧,所以我是C Sharp的新手,我有一個可能發送空值的函數調用。我想確保如果它爲空,那麼我應該將那些空值設置爲空字符串。以下是我嘗試過的方法,但我認爲必須有一種優雅的方式來實現這一點。當空值傳遞時如何設置空字符串
public static Concat()
{
// imagine x = null and y = null
Abc(x, y);
}
public static Abc (string x , string y)
{
// blah blah
x = x ?? "";
y = y ?? "";
efg(x, y);
}
我看着這個Solution,但我無法理解它。我可以在Abc arguments/parameter
本身做些什麼嗎?我的意思是
public static Abc (string x Can I do something here , string y Can I do something here)
{
// blah blah
x = x ?? "";
y = y ?? "";
efg(x, y);
}
不,你不能按照定義。如果你允許傳遞'string'(而'null'是一個字符串的有效值),那麼可以將null作爲參數值傳遞。你的示例代碼片段可以做到這一點:'x = x ?? 「」;''可以被讀爲「set x = x如果x不爲空,但是如果它爲空,則將其設置爲空字符串 – SlimsGhost
或者你可以通過簡單地使用」efg(x ??「」, y「」「);」 – SlimsGhost
C#不支持不可爲空的引用類型,假設它有hadm,那麼你的方法可能看起來像'public static Abc(string!x,string!y)',其中感嘆號這意味着編譯器保證它們不會爲null。有關未來C#特性的一些相關建議,請參閱例如[Proposal:Nullable reference types and nullability checking](https://github.com/dotnet/roslyn/issues/5032) –