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

时间:2017-11-06 15:06:04

标签: c#

我有2个课程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

2 个答案:

答案 0 :(得分:0)

正如@derloopkat建议的那样,您只需将 &#34; StaggingAttorney&#34; 实例投射到其父类。 ( &#34;律师&#34; 在这种情况下)

但是,如果你真的需要一个 &#34;律师&#34; 的新实例,其值与父 &#相同34; StaggingAttorney&#34; 只需访问 &#34; StaggingAttorney&#34; 对象的父字段。

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;
    }

}

答案 1 :(得分:0)

当您创建子类的实例时,您也在创建父类。因此,没有多少场景需要从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