【发布时间】:2014-10-28 01:28:25
【问题描述】:
我遇到过一些重复检查相同条件的代码。似乎 C# 6 将使我们摆脱这种丑陋的冗余代码,但与此同时,引入 bool 变量是否有任何好处,或者编译器是否足够聪明,可以为我们解决这个问题 而不是一遍又一遍地比较同样的事情? (即使我们无论如何都要进行检查,我会假设将结果存储在 bool 中会(略微)更快?)
// here we're doing the same check over and over again
string str1 = (CustomerData == null) ? string.Empty : CustomerData.str1;
string str2 = (CustomerData == null) ? string.Empty : CustomerData.str2;
string str3 = (CustomerData == null) ? string.Empty : CustomerData.str3;
// ... rinse and repeat
// here we're still doing a check, but against a boolean variable
bool is_valid = CustomerData == null;
string str1 = is_valid ? string.Empty : CustomerData.str1;
string str2 = is_valid ? string.Empty : CustomerData.str2;
string str3 = is_valid ? string.Empty : CustomerData.str3;
// ... rinse and repeat
在这种情况下,这可能并不重要,但如果要比较两个对象,然后需要深入检查其中的所有字段,会发生什么?
注意:由于这是在方法内部,我不能依赖字符串的默认值 (null),因此解决方法是创建所有字符串,并将它们初始化为
string.Empty,然后执行以下操作:
if (CustomerData != null) {
// set all of the above strings again, changing from empty to actual values
}
【问题讨论】:
-
旁注:null-objects 通常可以解决特定类型的检查:
CustomerData = CustomerData ? Data.Default;(其中Data.Default的所有“空”字段都填充了安全值)。 -
是的,
null-objects很酷,也应该有助于进行一些测试。将无法将它们实施到我当前的项目中,因为它太大了。因此,上面的问题:)
标签: c# performance compiler-optimization