我有以下界面:
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很常见,
我该怎么做?
谢谢,抱歉我的英语。
答案 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。)