簡體   English   中英

檢查對象不為null后,從該對象獲取屬性的最快方法是什么?

[英]What is the fastest way to get a property from an object after checking that the object isn't null?

在檢查對象不為null之后,從對象中獲取屬性的最快方法(就最大程度地減少代碼語句而言)是什么?

string s = null;

if (null != myObject)
{
    s = myObject.propertyName;
}

供參考:等待將來的C#6.0功能對可能的?.進行空檢查?. 句法:

string result = obj?.ToString();

現在:使用三元運算符

string result = obj != null ? obj.ToString() : null;

C#沒有空值傳播運算符(盡管已經討論了幾次)。 坦白地說,“更快”在這里不太可能成為一個因素,因為它通常會以相同(或足夠相似)的IL結束,但是我傾向於使用:

string s = myObject == null ? null : myObject.PropertyName;

您所描述的情況只是操作員有用的一種情況。 替換這樣的結構也很方便:

 if (value != null)
        {
            return value;
        }
        else
        {
            return otherValue;
        }

要么

return value != null ? value : otherValue;

return value ?? otherValue;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM