【发布时间】:2016-11-06 23:55:54
【问题描述】:
我有一个具有以下层次结构的 dll:
Interface ISchema {}
class Schema:ISchema{}
class TableSchema:Schema{}
class ViewSchema:Schema{}
我有另一个具有以下层次结构的 dll:
Interface ISearch {}
class Table:ISearch{}
class View:ISearch{}
以下代码是根据用户选择触发对Table或View的搜索操作:
private void FindNowButton_Click(object sender, EventArgs e)
{
// return Table or View according to user selection. (Property is an internal class helping to retrieve the selected type)
var type = (ObjectsTypeComboBox.SelectedItem as Property).Type;
// Create an instance of table or View as ISearch
var instance = (ISearch)Activator.CreateInstance(type);
// Call to relevant Search (table.Search or View.Search)
// _dataManager help to get the records from Schema hierarchy
// text is the text to search
var result = instance.Search(_dataManager, FindWhatTextBox.Text);
// Show in DataGridView the result
FindResultsDGV.DataSource = result;
}
每个搜索方法都返回一个列表。我需要在网格上显示不同的列。 TableSchema 和 ViewSchema 有不同的属性,下面的转换就可以了。
FindResultsDGV.DataSource = result.Cast<TableSchema> ; // or result.Cast<ViewSchema>
在这个阶段如何动态获取正确的类型?
欢迎任何其他解决方案
更新:
根据@GiladGreen
public interface ISearchSchemaFactory
{
ISearch<ISchema> GetSearch(Type schemaType);
}
public class Factory : ISearchSchemaFactory
{
public ISearch<ISchema> GetSearch(Type schemaType)
{
if (schemaType.Equals(typeof(Table)))
{
return new BL.AdvancedSearch.Table(); // Getting an error here
// Cannot implicitly convert type 'Table' to 'ISearch<ISchema>'. An explicit conversion exists (are you missing a cast?)
}
else if (schemaType.Equals(typeof(View)))
{
// TODO
}
return null; // TODO
}
}
【问题讨论】:
-
你考虑过使用泛型吗?
标签: c# .net oop interface polymorphism