c#速记,如果不为null,则赋值 [英] c# shorthand for if not null then assign value
问题描述
现在C#中是否有任何速记可以削减以下代码:
Is there any shorthand in c# now that will cutdown the following code:
var testVar1 = checkObject();
if (testVar1 != null)
{
testVar2 = testVar1;
}
在这种情况下,如果CheckObject()结果中的testVar1不为null,则只想分配testVar2(testVar2具有将触发代码的setter).试图思考如何使用null合并的东西,但没有真正解决问题.
In this situation only want to assign testVar2 if testVar1 is not null from the CheckObject() result (testVar2 has a setter that will fire off code). Was trying to think how could use the null coalesce stuff but not really working out.
添加到此testVar2的代码将在其设置程序上触发,因此,如果值为null,则不要将testVar2设置为任何值.
Adding on to this testVar2 has code on it's setter to fire, so do not want testVar2 being set to anything if the value is null.
public MyObj testVar2
{
get { return _testVar2; }
set
{
_testVar2 = value;
RunSomeCode();
}
}
推荐答案
有几个!
三元运算符:
testvar2 = testVar1 != null ? testvar1 : testvar2;
逻辑将完全相同.
或者,正如您所评论的,您可以使用空合并运算符:
Or, as commented you can use the null coalescing operator:
testVar2 = testVar1 ?? testVar2
(尽管现在也有评论)
或第三个选项:编写一次方法,然后按自己的意愿使用它:
Or a third option: Write a method once and use it how you like:
public static class CheckIt
{
public static void SetWhenNotNull(string mightBeNull,ref string notNullable)
{
if (mightBeNull != null)
{
notNullable = mightBeNull;
}
}
}
并命名为:
CheckIt.SetWhenNotNull(test1, ref test2);
这篇关于c#速记,如果不为null,则赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!