首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将基类的属性传递给派生类的更好方法?

将基类的属性传递给派生类的更好方法?
EN

Stack Overflow用户
提问于 2019-08-29 10:07:26
回答 2查看 850关注 0票数 3

考虑有以下代码:

公共类TheBase { public int 1{ get;set;} public int 2{ get;set;} public int 3{ get;set;}公共int 3{ get;set;}公共类派生: TheBase { public派生(TheBase theBase) {1= theBase.One;2= theBase.Two;3= theBase.Three;} public int 4{ get;set;} public int 5{get;set;}}

是否有更简单的方法将属性“1”、“2”和“3”从基类传递给派生类?是否有一种整洁的黑客,或这是最好的解决方案,这样的问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-29 10:13:49

这是适当的实施:

代码语言:javascript
运行
复制
public class TheBase
{
    public int One { get; set; }
    public int Two { get; set; }
    public int Three { get; set; }
    public TheBase(int one, int two, int three)
    {
        One = one;
        Two = two;
        Three = three;
    }
    public TheBase(TheBase theBase)
    {
        One = theBase.One;
        Two = theBase.Two;
        Three = theBase.Three;
    }
}
public class Derived : TheBase
{
    public int Four { get; set; }
    public int Five { get; set; }
    public Derived(TheBase theBase, int four, int five) : base(theBase)
    {
        Four = four;
        Five = five;
    }
    public Derived(int one, int two, int three, int four, int five) : base(one, two, three)
    {
        Four = four;
        Five = five;
    }
}
票数 9
EN

Stack Overflow用户

发布于 2019-08-29 13:00:00

只需处理派生类,就好像基类属性是在派生类中创建的一样。提示:使用适当的修饰符来保持事物的封装。类似于:

代码语言:javascript
运行
复制
public abstract class TheBase
{
   protected int baseOne { get; set; }
   protected int baseTwo { get; set; }
   protected int baseThree { get; set; }
}

public class Derived : TheBase
{
   public int Four { get; set; }
   public int Five { get; set; }

   public void SomeCode()
   {
       baseOne = 1;
       baseTwo = 2;
       baseThree = 3;
       Four = 4;
       Five = 5;
   }
}

(为了知道哪些属性来自基类,我使用了这个“基”前缀,但当然没有必要)。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57707836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档