c#在循环中按对象类型控制程序流l

时间:2015-10-03 07:21:50

标签: c#

我正在使用一个允许用户将C.V.s添加到公司数据库的系统。文档由部分组成,每个部分可以有一个或多个字段。字段对应于映射到特定字段类型的用户控件。用户控件没有以任何方式绑定到文档对象,并且从包含用户控件的页面将数据保存到文档中,有一个这样的方法:

public void SaveData(Document document)
{
    // Get all user controls on the page
    var userControls = FindDescendants<UserControl>(this);

    foreach (var section in document.Sections)
    {
        foreach (var field in section.Fields)
        {
            if (field is Address)
            {
                var address = field as Address;

                var addressControl = userControls.FirstOrDefault(o => o.ClientID.Contains(field.Id)) as AddressUserControl;
                addressControl.SaveData(address);
            }
            else if (field is TelephoneNumbers)
            {
                var telephoneNumbers = field as TelephoneNumbers;

                var telephoneNumbersControl = userControls.FirstOrDefault(o => o.ClientID.Contains(field.Id)) as TelephoneNumbersUserControl;
                telephoneNumbersControl.SaveData(telephoneNumbers);
            }
            ...
            ...
            else if (field is Employment)
            {
                var employment = field as Employment;

                var employmentControl = userControls.FirstOrDefault(o => o.ClientID.Contains(field.Id)) as EmploymentUserControl;
                employmentControl.SaveData(employment);
            }
        }
    }
}

我不喜欢嵌套循环,每次添加新字段类型时,foreach中的条件语句都会增长。

任何想法如何更优雅地构建它?

0 个答案:

没有答案