C# 中是否有一个操作符,其行为类似于 groovy 中的安全导航操作符?
例如,在 groovy 中,如果 SessionData.CurrentSeminar 为 null,则执行此类操作将阻止它获得 NullPointerException。
int respId = SessionData.CurrentSeminar?.SeminCbaRespId;
这是如何用 C# 完成的?
C# 中是否有一个操作符,其行为类似于 groovy 中的安全导航操作符?
例如,在 groovy 中,如果 SessionData.CurrentSeminar 为 null,则执行此类操作将阻止它获得 NullPointerException。
int respId = SessionData.CurrentSeminar?.SeminCbaRespId;
这是如何用 C# 完成的?
该运算符在 C# 中不存在。你可以用 inline-if 来做到这一点
int respId = SessionData.CurrentSeminar != null ?
SessionData.CurrentSeminar.SeminCbaRespId : default(int);
或作为扩展方法。
var respId = SessionData.CurrentSeminar.GetSeminCbaRespId();
public static int GetSeminCbaRespId(this typeofCurrentSeminar CurrentSeminar)
{
return CurrentSeminar != null ? CurrentSeminar.SeminCbaRespId : default(int);
}
也许像这样的解决方法?
int respId= ReferenceEquals(SessionData.CurrentSeminar,null)?-1:SessionData.CurrentSeminar.SeminCbaRespId;
没有运营商,但你可以接近。试试这个答案中的一个:
int respId = SessionData.CurrentSeminar.NullOr(s => s.SeminCbaRespId) ?? 0;
如果您需要链接其中的几个,这将变得特别有用:
var elem = xml.Element("abc")
.NullOr(x => x.Element("def"))
.NullOr(x => x.Element("blah");
最接近的运算符是?:
,但它没有那么含糖。
所以,你可以这样做:
int respId = SessionData.CurrentSeminar != null ? SessionData.CurrentSeminar.SeminCbaRespId : 0; // if 0 is the "null" value