首页 > 解决方案 > 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?
    }
}

标签: c#

解决方案


如果您需要知道特定类型,那么您可能没有很好地利用接口,但是:您可以执行以下操作:

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 */ }
}

强调:在这种情况下,您通常应该避免需要知道特定类型是什么。这意味着您实际上并未对界面进行编码。


推荐阅读