Mat*_*att 15 c# null-coalescing-operator null-coalescing shorthand
现在 C# 中是否有任何速记可以减少以下代码:
var testVar1 = checkObject();
if (testVar1 != null)
{
testVar2 = testVar1;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果从 CheckObject() 结果中 testVar1 不为空,则只想分配 testVar2(testVar2 有一个将触发代码的设置器)。试图思考如何使用空合并的东西,但没有真正解决。
添加到此 testVar2 的 setter 上有要触发的代码,因此如果值为 null,则不要将 testVar2 设置为任何内容。
public MyObj testVar2
{
get { return _testVar2; }
set
{
_testVar2 = value;
RunSomeCode();
}
}
Run Code Online (Sandbox Code Playgroud)
Aus*_*nch 21
有一对!
三元运算符:
testvar2 = testVar1 != null ? testvar1 : testvar2;
Run Code Online (Sandbox Code Playgroud)
将是完全相同的逻辑。
或者,正如所评论的,您可以使用空合并运算符:
testVar2 = testVar1 ?? testVar2
Run Code Online (Sandbox Code Playgroud)
(虽然现在也有人评论了)
或者第三种选择:编写一次方法并按照您的喜好使用它:
public static class CheckIt
{
public static void SetWhenNotNull(string mightBeNull,ref string notNullable)
{
if (mightBeNull != null)
{
notNullable = mightBeNull;
}
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
CheckIt.SetWhenNotNull(test1, ref test2);
Run Code Online (Sandbox Code Playgroud)
Ste*_*ieG 10
我在 google 上搜索了“c#shorthand set if null”并首先登陆这里,所以只是为了其他人。问题是“if NOT null 然后赋值的简写”,下面是“if null 然后赋值的简写”。
在 C# 8.0+ 中,您可以使用??=:
// Assign testVar1 to testVar2, if testVar2 is null
testVar2 ??= testVar1;
// Which is the same as:
testVar2 = testVar2 ?? testVar1;
// Which is the same as:
if(testVar2 == null)
{
testVar2 = testVar1;
}
Run Code Online (Sandbox Code Playgroud)
还有我最喜欢的:
// Create new instance if null:
testVar1 ??= new testClass1();
// Which is the same as:
if(testVar1 == null)
{
testVar1 = new testClass1();
}
Run Code Online (Sandbox Code Playgroud)
只是一个我经常使用的例子:
List<string> testList = null;
// Add new test value (create new list, if it's null, to avoid null reference)
public void AddTestValue(string testValue)
{
testList ??= new List<string>();
testList.Add(testValue);
}
Run Code Online (Sandbox Code Playgroud)