想知道是否有更好的方法来处理多个类似的条件语句和操作,例如下面的示例代码片段。
private void AddCommonDictionaryItemsForAllAttributes(MyCustomType dc, string statusFlag)
{
if (dc.xmlAttributes == null) {
dc.xmlAttributes = new Dictionary<string, string>();
}
dc.xmlAttributes.Add(Constant.CD_1, statusFlag);
dc.xmlAttributes.Add(Constant.CD_2, statusFlag);
dc.xmlAttributes.Add(Constant.CD_3, statusFlag);
if (dc.primaryZone != null) {
dc.xmlAttributes.Add(Constant.CD_4, statusFlag);
}
if (dc.Mgr1 != null) {
dc.xmlAttributes.Add(Constant.CD_10, statusFlag);
}
if (dc.Mgr2 != null) {
dc.xmlAttributes.Add(Constant.CD_11, statusFlag);
}
if (dc.Mgr3 != null) {
dc.xmlAttributes.Add(Constant.CD_5, statusFlag);
}
if (dc.Producer != null) {
dc.xmlAttributes.Add(Constant.CD_6, statusFlag);
}
if (dc.CountTest > 0) {
dc.xmlAttributes.Add(Constant.CD_7, statusFlag);
}
if (dc.List1 != null && dc.List1.Count > 0) {
dc.xmlAttributes.Add(Constant.CD_8, statusFlag);
}
if (dc.List2 != null && dc.List2.Count > 0) {
dc.xmlAttributes.Add(Constant.CD_9, statusFlag);
}
}
在我看来,if 条件和添加字典操作似乎是多余的,因此请寻找更高效、更优雅的方法来编码。
谢谢!
更新:我正在使用 .NET 3.5
最佳答案
您可以创建一个帮助程序类型,它提供要在 MyCustomType
实例上执行的测试,以及要在 xmlAttributes
字典中使用的键:
class Rule
{
private readonly Predicate<MyCustomType> _test;
private readonly string _key;
public Predicate<MyCustomType> Test { get { return _test; } }
public string Key { get { return _key; } }
public Rule(Predicate<MyCustomType> test, string key)
{
_test = test;
_key = key;
}
}
然后您可以创建一组这些规则,并枚举它们:
private void AddCommonDictionaryItemsForAllAttributes(MyCustomType dc, string statusFlag)
{
var rules = new Rule[]
{
new Rule(x => x.Mgr1 != null, Constant.CD_4),
new Rule(x => x.Mgr2 != null, Constant.CD_10),
//...snip...
new Rule(x => x.List2 != null && x.List2.Count > 0, Constant.CD_9)
};
foreach(var rule in rules.Where(r => r.Test(dc)))
dc.xmlAttributes.Add(rule.Key, statusFlag);
}
关于c# - 避免连续、相似条件 block 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5000925/