一個相當簡短的問題。C++/CLI良好的編碼習慣,索引屬性if-check或try..catch?
讓我們使用這段代碼:
public ref class Foo
{
private:
System::Collections::Generic::Dictionary<System::String ^,System::String ^>^aDictionary;
public:
property System::String^SomeIndexedProperty[System::String ^]
{
public: System::String^get(System::String^index)
{
return aDictionary[index];
}
}
public:
Foo(void)
{
aDictionary = gcnew System::Collections::Generic::Dictionary<System::String ^,System::String ^>();
}
};
它會更好包圍/前檢查與if語句(if(aDictionary->ContainsKey(index))
退貨或者倒不如包圍return語句用一試。 .catch塊?
在這兩種情況下返回nullptr時,他們會失敗。
速度是不是真正的問題的。但只是一般的「這是因爲這個原因更好」就足夠了。
在絕大多數情況下,返回nullptr是錯誤的。添加一個HasValue()方法,以便客戶端代碼可以發現該值不存在。如果用法指示該值始終存在,則不要執行任何操作,以便客戶端程序員可以輕鬆修復其錯誤。 – 2011-02-09 12:14:05