【问题标题】:Access inherited member访问继承的成员
【发布时间】:2019-06-01 20:28:13
【问题描述】:

我有这个继承自 LoanLoanWithClient 模型:

public class LoanWithClient : Loan
{
    public Client Client { get; set; }
}

如何访问整个继承的Loan 对象,而无需显式编写其属性?

LoanWithClient 不包含 Loan 的定义

return new LoanWithClient
{
     **Loan** = loan, //The Loan is erroring: LoanWithClient does not contain a definition for Loan
     Client = client
};

班级贷款:

public class Loan
{
    public int ID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    //etc..
}

【问题讨论】:

  • Loan的帖子定义
  • 我想你可能误解了“继承”的含义。这意味着派生类 (LoanWithClient) 具有其父类 (Loan) 的特性(方法、属性等)。如果LoanWithClientLoan 都没有属性Loan,那么在构造实例时将无法使用它。如果Loan 具有Amount 属性,您可以像使用Client 一样直接使用它。
  • 创建一个构造函数并从中调用基类构造函数。参见例如stackoverflow.com/questions/12051/…
  • 另外,您的对象模型看起来有点可疑。地址真的是贷款的财产吗?
  • 不要混淆 is-ahas-aLoanWithClient Loan。它没有Loan

标签: c#


【解决方案1】:

LoanWithClient 类继承自 Loan。这意味着子类具有父类的所有属性。但这并不意味着子类包含一个父类作为属性。你可以这样写类-

public class Loan
{
    public int ID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    //etc..
}

public class LoanWithClient
{
    public Loan Loan { get; set; }
    public Client Client { get; set; }
}

return new LoanWithClient
{
     Loan = loan,
     Client = client
};

如果你想保留你的类架构,你可以像下面这样返回-

return new LoanWithClient
{
     ID = loan.ID,
     Address = loan.Address,
     City = loan.City,
     //etc..
     Client = client
};

【讨论】:

    【解决方案2】:

    你想要

    访问继承的成员

    Loan 不是成员,它是父级。 像这样访问 Loan 的成员:

    return new LoanWithClient
    {
         ID = loan.ID,
         Address = loan.Address,
         City = loan.City,
         //etc...
         Client = client
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 2019-12-19
      相关资源
      最近更新 更多