c# - 避免连续、相似条件 block 的方法

标签 c# design-patterns generics .net-3.5 if-statement

想知道是否有更好的方法来处理多个类似的条件语句和操作,例如下面的示例代码片段。

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/

相关文章:

java - Lotus Notes 日历报告

c# - 如何将作为参数传递的 KeyValuePair 转换为 Command_Executed?

java - 如何改进 builder 模式?

java - 对象化,Key<T> 可能吗?解决方法?

java - 为什么 Function.identity() 会破坏类型具体化,而 t -> t 却不会?

c# - 重新排序列表中项目的正确方法(nhibernate)

c# - 如何在 C# 中解码包含 XML 文档的 base64 编码字符串,该文档包含带有重音符号 (á,é,í,ó,ú) 的字符?

java - 为我的类中使用的通用 pojo 建模

php - 面向 OO-PHP 和 WordPress 插件的 MVC 方法

c# - 为什么 C# 中的计数器(使用 CRTP)不会对某些类型的对象进行倒计时?