【发布时间】:2011-09-06 16:12:30
【问题描述】:
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吗?
我的问题:
如何用 ?: ?? 编写以下内容运营商
[1]
if ( Source == null ){
// Return Nothing
} else {
return Source;
}
[2]
if ( Source == value ){
// Do Nothing
} else {
Source = value;
RaisePropertyChanged ( "Source" );
}
简述:如何使用?:??操作符什么都不做,什么都不返回,执行多条指令?
【问题讨论】:
-
它的行为不会相同。通过不使用条件 if/else 分支,您每次访问它时都会无条件地(并且不必要地)重新分配变量。这可能很快就会变糟,尤其是在您拥有多线程代码的情况下。只是不要这样做。
-
如果 Source 属性的 get 访问器正在返回 Source 属性(它的 get 访问器),您将进行无休止/递归调用。
-
您的第一个代码 sn-p 有一个属性 getter,它调用自己的 setter,而后者又递归调用自己的 getter。你把我弄丢了,因为那样的东西不可能在现场起作用。请完善您的问题并准确解释您想要实现的目标。
-
什么都不返回?那是VB。你在这里写 c#。
-
@Task 我的意思是怎么做,这一行是对问题的评论
标签: c# ternary-operator