自动化铸造类型

时间:2011-08-08 05:13:59

标签: c#

我有以下界面:

public interface IDataAccessor
    {
        IList GetAllRecords();
        IFormEditor ShowAddEditForm();


    }

和继承此接口的类:

 public class LanguageDataAccessor : IDataAccessor
    {

        public void SaveLanguage(Languages language)
        {
            LanguagesDAO languages = new LanguagesDAO();
            languages.Save(language);
        }
    // other methods...
}

在用户控件中,我有以下代码:

public partial class ucDisplayDictionary : UserControl
    {
        public Type DictionaryName { get; set; }
        public IDataAccessor DataAccessor { get; set; } 

public ucDisplayDictionary(IDataAccessor accessor)
            : this()
        {
            DataAccessor = accessor;
            DictionaryName = accessor.GetType();
        }

private void btnEditRecord_Click(object sender, EventArgs e)
         {
             if (dgvDisplayDictionary.CurrentRow != null)
             {
                 var frmEdit = DataAccessor.ShowAddEditForm();

                 frmEdit.SetValue(dgvDisplayDictionary.CurrentRow.DataBoundItem);                    

                 if (frmEdit.GetForm().ShowDialog() == DialogResult.OK)
                 {
                     dgvDisplayDictionary.DataSource = null;
                     dgvDisplayDictionary.DataSource = ((LanguageDataAccessor)DataAccessor).Collection; // *                           
                 }
             }    
         }

在字符串(*)中我想写类似的东西:

dgvDisplayDictionary.DataSource = ((DictionaryName)DataAccessor).Collection;

因为此用户控件对于其他DataAccessor很常见,

我该怎么做?
谢谢,抱歉我的英语。

1 个答案:

答案 0 :(得分:1)

如果您的所有IDataAccessor实施都具有Collection属性,则应将该属性放在IDataAccessor中 - 然后根本不需要转换。

如果您的Collection属性是强类型的,则可能需要以下内容:

public interface IDataAccessor
{
    IList GetAllRecords();
    IFormEditor ShowAddEditForm();
    IList Collection { get; }
}

public interface IDataAccessor<T> : IDataAccessor
{
    new IList<T> Collection { get; }
}

(与IEnumerator具有非通用Current的方式相同,而通用IEnumerator<T>具有通用属性。)

这样,以强类型方式需要集合的任何内容都可以使用IDataAccessor<T>,但您不需要使ucDisplayDictionary类具有通用性。 (我建议你重命名,以便遵循.NET惯例 - 目前看起来很可怕。)

您的IDataAccessor.GetAllRecords()方法可能已经满足了您的需求,您只需要将代码更改为:

 dgvDisplayDictionary.DataSource = DataAccessor.GetAllRecords();

(顺便说一下,你不需要先将DataSource设置为null。)