3 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
在C#6中,可以使用Null條件運(yùn)算符。因此原始測(cè)試將是:
int? value = objectA?.PropertyA?.PropertyB?.PropertyC;

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以在類中添加方法嗎?如果沒有,您是否考慮過使用擴(kuò)展方法?您可以為您的對(duì)象類型創(chuàng)建一個(gè)擴(kuò)展方法,稱為GetPropC()。
例:
public static class MyExtensions
{
public static int GetPropC(this MyObjectType obj, int defaltValue)
{
if (obj != null && obj.PropertyA != null & obj.PropertyA.PropertyB != null)
return obj.PropertyA.PropertyB.PropertyC;
return defaltValue;
}
}
用法:
int val = ObjectA.GetPropC(0); // will return PropC value, or 0 (defaltValue)
順便說一句,這假設(shè)您使用的是.NET 3或更高版本。
- 3 回答
- 0 關(guān)注
- 1348 瀏覽
添加回答
舉報(bào)