简体   繁体   English

继承与收藏

[英]Inheritance and Collections

I have an inheritance problem. 我有一个继承问题。
I started with something similar to: 我从类似以下内容开始:

public class POpt
{
...
    private decimal profit;
    public decimal Profit
    {
        get { return profit; }
    }
...
}

public class Opt
{
...
    private List<POpt> pases;

    public int NumPasesPositivos()
    {
        return pases.Where(o => o.Profit > 0).Count();
    }
...     
}

And it works .. I can call NumPasesPositivos() and get the number of pases with positive profit in the List pases. 它有效..我可以调用NumPasesPositivos()并在List步数中获取具有正利润的步数。

Right now, I have to write two similar classes like Popt and Opt... and use inheritance: 现在,我必须编写两个类似的类,例如Popt和Opt ...并使用继承:

abstract public class P
{
...
...
}

public class POpt: P
{
...
    private decimal profit;
    public decimal Profit
    {
        get { return profit; }
    }
...
}

public class PBt: P
{
...
...
}

And also: 并且:

abstract public class T
{
...
    private List<P> pases;
...     
}

public class Opt: T
{
...
    public int NumPasesPositivos()
    {
        return pases.Where(o => o.Profit > 0).Count();
    }
...     
}

public class Bt:T
{
...
...     
}

Now, the list in the class T pases, can be a POpt or PBt clases list. 现在,类别T类别中的列表可以是POpt或PBt类别列表。 Problem is that right now, I can´t use NumPasesPositivos because pases can be POpt or PBt and Profit its not defined in PBt, and I cant cast 问题是,现在,我不能使用NumPasesPositivos,这是因为pases可以是POpt或PBt,Profit在PBt中未定义,因此我无法进行投射
pases in OPt to someting like (List<POpt>pases).Where(o => o.Profit > 0).Count() ....Im not sure how to solve the problem nor how to rewrite the classes... 在OPt中出现类似(List <POpt> pases)的东西。where(o => o.Profit> 0).Count()....我不确定如何解决问题或如何重写类...

You can use the OfType extension method and restrict to types that can be cast to POpt . 您可以使用OfType扩展方法并将其限制为可以POptPOpt类型。

public int NumPasesPositivos()
{
    return pases.OfType<POpt>().Where(o => o.Profit > 0).Count();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM