?:??运营商,而不是IF | ELSE [英] ?: ?? Operators Instead Of IF|ELSE
问题描述
public string Source
{
get
{
/*
if ( Source == null ){
return string . Empty;
} else {
return Source;
}
*/
return Source ?? string.Empty;
}
set
{
/*
if ( Source == null ) {
Source = string . Empty;
} else {
if ( Source == value ) {
Source = Source;
} else {
Source = value;
}
}
*/
Source == value ? Source : value ?? string.Empty;
RaisePropertyChanged ( "Source" );
}
}
我可以使用?:
??
运营商的完全为的if / else?
Can I use ?:
??
operators EXACTLY as If/Else?
我的问题:结果
如何写下列要求:??运营商
My Question :
How to write the following with ?: ?? operators
[1]
if ( Source == null ){
// Return Nothing
} else {
return Source;
}
[2]
if ( Source == value ){
// Do Nothing
} else {
Source = value;
RaisePropertyChanged ( "Source" );
}
简单:如何什么都不做,什么都不返回并做多条指令:<?/ code>
??
运营商
Briefly : How to do nothing, return nothing and do multiple instructions with ?:
??
operator?
推荐答案
有关[1],你不能。这些运营商都是为了返回一个值,不执行操作。
For [1], you can't: these operators are made to return a value, not perform operations.
表达
a ? b : c
计算结果为 B
如果 A
是真实的,如果 A
是假的计算结果为 C
。
evaluates to b
if a
is true and evaluates to c
if a
is false.
表达式
b ?? c
计算结果为 B
$ C> b 不是null,计算结果为 C
如果 b
为null。
evaluates to b
if b
is not null and evaluates to c
if b
is null.
如果你写
return a ? b : c;
或
return b ?? c;
他们会的总是的返回值。
有关[2],您可以编写返回执行你的多个操作正确的价值功能,但是这可能更糟比只使用的if / else
。
For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else
.
这篇关于?:??运营商,而不是IF | ELSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!