许多类似对象的实体无论如何都可以使它们共享接口



我有一个连接到 4 个数据库的程序。在其中三个数据库中,实体对象非常相似。现在我的问题很简单,但我无法弄清楚如何继续。

我有三个数据库,我们称它们为 1 2 和 3在那些我得到几个表 a b 和 c

我问既然 1a 和 2a 和 3a 几乎相同,我有没有办法做这样的事情。

Using(interfaceDB DB = new DB1())
{
   var getTabelA = (from a in DB.a select a);
}
Using(interface DB = new DB2())
{
   var getTabe2A = (from a in DB.a select a);
}
Using(interface DB = new DB3())
{
   var getTabe3A = (from a in DB.a select a);
}
foreach(interfaceDBTableA in getTabelA)
{
   //do something here
}
foreach(interfaceDBTableA in getTabe2A )
{
   //do something here
}
foreach(interfaceDBTableA in getTabe3A )
{
   //do something here
}

基本上,我的希望是我可以将循环部分放入它自己的方法中并重用它,而无需将其自定义为单个表?

您可以定义一个接口,其中包含对象共有的成员,如下所示:

public interface ICommonStuff
{
    int CommonInt
    {
        get;
    }
    string CommonString
    {
        get;
    }
}

。然后在类ABC中实现该接口:

public class A : ICommonStuff
{
    public int AInt { get; set; }
    public string AString { get; set; }
    public int CommonInt
    {
        get { return this.AInt; }
    }
    public string CommonString
    {
        get { return this.AString; }
    }
}
public class B : ICommonStuff
{
    public int BInt { get; set; }
    public string BString { get; set; }
    public int CommonInt
    {
        get { return this.BInt; }
    }
    public string CommonString
    {
        get { return this.BString; }
    }
}
... (same for C)

然后,您应该能够像这样选择它们:

using (interfaceDB DB = new DB1())
{
    var getTable1A = (from a in DB.a select a).Cast<ICommonStuff>();
}
using (interface DB = new DB2())
{
    var getTable2A = (from a in DB.a select a).Cast<ICommonStuff>();
}
using (interface DB = new DB3())
{
    var getTable3A = (from a in DB.a select a).Cast<ICommonStuff>();
}
var everythingLikeA = getTable1A.Concat(getTable2A).Concat(getTable3A);
foreach (ICommonStuff commonStuff in everythingLikeA)
{
    // do something here with commonStuff.CommonInt and commonStuff.CommonString
}

相关内容

最新更新