c# - C# 返回不同的对象并使用它
问题描述
我被困在一个问题上。我有一种查询表的方法。而且我有代表表的类,它们都派生自一个 interface ITable
。该方法返回IEnumerable<ITable>
。但是我不能使用 return 给出的对象,这就是我的意思:
public interface ITable
{
}
public class table1 : ITable
{
prop1 {get;set;}
}
public class table2 : ITable
{
prop2 {get; set;}
}
public IEnumerable<ITable> GetInfo(string table)
{
switch(table)
{
case "Table1":
var dataTable1 = connection.Query<Table1> ....
return dataTable1;
case "Table2":
var dataTable2 = connection.Query<Table2> ....
return dataTable2;
}
}
static void Main(string[] args)
{
foreach (var table in listOfTable)
{
var data = GetInfo(table);
//data here is "Table" how can i make the mthod to return my Table1 or Table2?
}
}
解决方案
如果您需要知道特定类型,那么您可能没有很好地利用接口,但是:您可以执行以下操作:
var data = GetInfo(table);
foreach(var item in data)
{
if (item is table1 t1) { /* special code for table1, now held as t1 */ }
else if (item is table2 t2) { /* special code for table2, now held as t2 */ }
else {/* general code for ITable */ }
}
强调:在这种情况下,您通常应该避免需要知道特定类型是什么。这意味着您实际上并未对界面进行编码。
推荐阅读
- c++ - 无法使用子类中定义的虚拟 getter 实现基类
- active-directory - Active Directory 中的哪些字段不仅是唯一的,而且是不可变的 (ADFS)
- java - 带有字符串和整数的评估顺序
- python - 使用字典和数据框通过循环创建具有变量名的新数组
- python - 如何使用 cython 编译 python 并避免 Windows 上的导入限制?
- mongodb - 如何将 mongo 容器暴露在覆盖网络之外?
- github - Github action bot 推送到 gh-pages 导致页面构建失败
- python - 3D 中的 FancyArrowPatch
- tensorflow - 我正在研究多类文本分类,如何将一个热编码传递给 keras 模型以在 ytrainset 中进行训练?
- java - 搜索标题包含关键字的书籍并按标题排序(按字母顺序)返回