繁体   English   中英

C#仅基于派生类提取基类属性并返回新的基类对象

[英]c# extract base class properties only based on derived class and return new base class object

我有两个班StaggingAttorneyAttorney 我将使用StaggingAttorney收集有关律师的信息,一旦获得所有信息,我将使用它来创建最佳结果的Attorney个人资料。 这两个类如下所示;

private class StaggingAttorney : CourtCase.Attorney
{
    public bool scraping = false;

    public bool scraped = false;

    public string caseNumber;

    public CourtCase.Attorney toAttorney()
    {
        CourtCase.Attorney attorney = new CourtCase.Attorney();
        return attorney;
    }

}

...和...

public class Attorney
{
    public string names;
    public string matchString;
    ...    
    public List<Identity> IdentityMatches = new List<Identity>();

    public List<Identity> getIdentityMatches()
    {
        return IdentityMatches;
    }
    public class Identity
    {
        public string names;
        public string barNumber;
        public string email;

        public string phoneNumber { get; internal set; }
        public object faxNumber { get; internal set; }
    }
}

我创建了一个名为CourtCase.Attorney toAttorney()的方法,您可以在上面看到。 在这种方法我想回到一个新的CourtCase.Attorney所有CourtCase.Attorney在继承的属性StaggingAttorney

正如@derloopkat建议的那样,您只需将您的“ StaggingAttorney”实例强制转换为他的父类。 (在这种情况下为“律师”

但是,如果您确实需要一个具有与父“ StaggingAttorney”相同值的“律师”的新实例,只需访问“ StaggingAttorney”对象的父字段即可

private class StaggingAttorney : CourtCase.Attorney
{
    public bool scraping = false;

    public bool scraped = false;

    public string caseNumber;

    public CourtCase.Attorney toAttorney()
    {
        CourtCase.Attorney attorney = new CourtCase.Attorney()
        {
            names = this.names,
            matchString = this.matchString,
            [... Initialize the other properties ...]
        };
        return attorney;
    }

}

当创建子类的实例时,您也在创建父类。 因此,在许多情况下,您无需通过child.ToParent()方法创建另一个新实例。 当一个类没有从另一个类继承时,使用这样的转换方法更有意义。

var attorney = new StaggingAttorney() { scraped = false };
attorney.names = "John"; //During the scraping process
attorney.scraped = true;
CourtCase.Attorney court = (CourtCase.Attorney)attorney; //casting
Console.WriteLine(court.names); //returns "John"

无需复制数据,因为子级从其父级继承了names

暂无
暂无

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

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