派生类的集合

时间:2016-03-10 16:26:45

标签: c# collections derived-class

我正在重构我的关注分离代码(SoC)。将非AutoCAD代码移动到单独的dll,因此Common,Data Access,Web服务,AutoCAD相关,...在不同的dll文件中。

以下是我班级的样本:

// non-AutoCAD dll
public class Loc
{
    public int Id;
    public string Name;
    ...
}

// AutoCAD dll
public class AcadLoc : Loc
{
    public ObjectId oid;
}

// non-AutoCAD dll
public class Locs : List<Loc>
{
    public Loc Get_By_Id(long id)
    {
        return this.SingleOrDefault(n => n.Id == id);
    }
}

// AutoCAD dll
public class AcadLocs : Locs // or List<AcadLoc> ? 
{
}

我的问题是,我可以运行类似

的内容
AcadLocs myAcadLocs = new AcadLocs();
AcadLoc myAcadLoc = myAcadLocs.Get_By_Id(1);   // How to make this works? 

我试过了:

public class AcadLocs : Locs // or List<AcadLoc> ? 
{
    public AcadLoc Get_By_Id(int id)
    {
        return this.SingleOrDefault(n => n.Id == id);
    }
}

它不会起作用。

现在我改为:

public interface ILocData<T> where T : new() {} 

// non-AutoCAD dll
public class Loc : ILocData<Loc>
{
    public int Id;
    public string Name;
    ...
}

// AutoCAD dll
public class AcadLoc : Loc, ILocData<AcadLoc>
{
    public ObjectId oid;
}

public class LocDataCollection<T, TCollection> : List<T>
    where T : ILocData<T>, new()
    where TCollection : LocDataCollection<T, TCollection>, new()
{
}

// non-AutoCAD dll
public class Locs : LocDataCollection<Loc, Locs>
{
    public Loc Get_By_Id(int id)
    {
        return this.SingleOrDefault(n => n.Id == id);
    }

    public bool Check()
    {
        foreach (Loc loc in this)
        {
        ....
        }
    }
}

// AutoCAD dll  
public class AcadLocs : LocDataCollection<AcadLoc, AcadLocs>
{
    public AcadLoc Get_By_Id(int id)
    {
        return this.SingleOrDefault(n => n.Id == id);
    }
}

现在,

AcadLoc myAcadLoc = myAcadLocs.Get_By_Id(1);   // works

myAcadLocs.Check();  // failed

由于

韦斯

2 个答案:

答案 0 :(得分:1)

我认为你需要的是扩展方法

public static class MyExtension 

{
    public static Loc Get_By_Id(this Locs l,int id) 
    {
        return l.SingleOrDefault(n => n.Id == id);
    }

    public static bool Check(this Locs l)
    {
        foreach (Loc loc in l)
        {
        ....
        }
    }
}

一旦你有了这个代码,那么就像这样调用这个方法

 myAcadLocs.Get_By_Id(1);
 myAcadLocs.Check();
 myLocs.Get_By_Id(1);
 myLocs.Check();

答案 1 :(得分:1)

我指的是你的第一次尝试。

1。继承

public class AcadLocs : Locs // or List<AcadLoc> ? 

如果您想从LocsList<AcadLoc>派生,取决于您希望如何使用此课程。如果您想声明公共成员,或者您是否有必要将AcadLocs的实例分配给Locs类型的变量

Locs locs = new AcadLocs();

然后你肯定需要从Locs派生。

2。 Get_By_Id

对于这种方法,我会使用OfType<>方法,如下所示:

public class AcadLocs : Locs // or List<AcadLoc> ? 
{
    public AcadLoc Get_By_Id(int id)
    {
        return this.OfType<AcadLoc>().SingleOrDefault(n => n.Id == id);
    }
}

OfType<AcadLoc>从现有序列中创建IEnumeralbe<AcadLoc>,仅选择具有指定类型(AcadLoc)的元素。这也可以帮助您使用Check方法。

相关问题