方法调用在C#中如果不为空 [英] Method call if not null in C#
问题描述
是否有可能以某种方式缩短这个声明?
如果(OBJ!= NULL)
obj.SomeMethod ();
因为我碰巧写这个了很多,它得到烦了。我能想到的唯一的事情是要落实空对象的模式,但是这不是我能做些什么,每次和它肯定不是缩短语法的解决方案。
和类似的问题与事件,其中
公共事件Func键<串GT; MyEvent;
,然后调用
如果(MyEvent!= NULL)
MyEvent.Invoke();
从C#6起,你可以使用:
MyEvent .Invoke()?;
或
OBJ .SomeMethod()?;
的
?
是空传播运营商,并会导致 .Invoke()
来短路时,操作数是空
。操作数只能被访问一次,所以不存在问题检查并调用之间价值变动的风险。
===
此前C#6,没有:没有空安全的法宝,但有一个例外;扩展方法 - 例如:
公共静态无效SafeInvoke(这个动作动作){
如果(行动= NULL )动作();
}
现在,这是有效的:
动作ACT = NULL;
act.SafeInvoke(); //什么都不做
ACT = {委托Console.WriteLine(HI);}
act.SafeInvoke(); //写HI
在事件的情况下,这个也有去除比赛中的优势-condition,也就是说,你并不需要一个临时变量。所以通常你需要:
VAR处理器= SomeEvent;
如果(处理!= NULL)处理(这一点,EventArgs.Empty);
但有:
公共静态无效SafeInvoke(此事件处理程序处理程序,对象发件人){
如果(处理!= NULL)处理器(发件人,EventArgs.Empty);
}
我们可以用简单的:
SomeEvent.SafeInvoke(本); //无竞争状态,没有空的风险
Is it possible to somehow shorten this statement?
if (obj != null)
obj.SomeMethod();
because I happen to write this a lot and it gets pretty annoying. The only thing I can think of is to implement Null Object pattern, but that's not what I can do every time and it's certainly not a solution to shorten syntax.
And similar problem with events, where
public event Func<string> MyEvent;
and then invoke
if (MyEvent != null)
MyEvent.Invoke();
From C# 6 onwards, you can just use:
MyEvent?.Invoke();
or:
obj?.SomeMethod();
The ?.
is the null-propagating operator, and will cause the .Invoke()
to be short-circuited when the operand is null
. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.
===
Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:
public static void SafeInvoke(this Action action) {
if(action != null) action();
}
now this is valid:
Action act = null;
act.SafeInvoke(); // does nothing
act = delegate {Console.WriteLine("hi");}
act.SafeInvoke(); // writes "hi"
In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:
var handler = SomeEvent;
if(handler != null) handler(this, EventArgs.Empty);
but with:
public static void SafeInvoke(this EventHandler handler, object sender) {
if(handler != null) handler(sender, EventArgs.Empty);
}
we can use simply:
SomeEvent.SafeInvoke(this); // no race condition, no null risk
这篇关于方法调用在C#中如果不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!