I have a following interface:
public interface IDataAccessor
{
IList GetAllRecords();
IFormEditor ShowAddEditForm();
}
and class which inheritance this interface:
public class LanguageDataAccessor : IDataAccessor
{
public void SaveLanguage(Languages language)
{
LanguagesDAO languages = new LanguagesDAO();
languages.Save(language);
}
// other methods...
}
In user control I have the following code:
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; // *
}
}
}
In the string (*) I want to write something like that:
dgvDisplayDictionary.DataSource = ((DictionaryName)DataAccessor).Collection;
because this user control is common for other DataAccessor,
How can I do this?
Thanks and sorry for my english.
If all your
IDataAccessorimplementations have aCollectionproperty, you should put that property inIDataAccessor– then you don’t need a cast at all.If your
Collectionproperty is strongly typed, you might want something like:(In the same way as
IEnumeratorhas the non-genericCurrent, and the genericIEnumerator<T>has the generic property.)That way anything which needs the collection in a strongly typed way can use
IDataAccessor<T>but you don’t need to make yourucDisplayDictionaryclass generic. (I suggest you rename that to follow .NET conventions by the way – it looks ghastly at the moment.)It’s possible that your
IDataAccessor.GetAllRecords()method already does what you want of course, and you only need to change your code to:(You don’t need to set the
DataSourceto null first, by the way.)