【问题标题】:How can I set default value to an attribut in the parent constructor?如何在父构造函数中为属性设置默认值?
【发布时间】:2022-01-08 18:44:41
【问题描述】:

我有两个构造函数:

public abstract class A
{
    public A(int a,int b = 0 ) {}
} 

public class B : A
{
    public B(int a , int b):base(a,b) {} // I would like to didn't call again the attribute b 
       // because it's set to 0 in the parent class 
      //   public B(int a):base(a) {} 
}

也许我的问题很荒谬,但我正在寻找一个技巧来避免在父类中重复调用默认设置为 0 的属性,事实上,我有很多子类

有可能吗?

更新:

这是在 MainWindow 中创建的 B 实例:

B b1 = new B(1); // a = 1 and b = 0 by default 
B b2 = new B(2,1) // I would like to update the value b and set it to 1 for in the second instance created , In this case I got an error 
// B does not contains a constructor that takes 2 arguments ...

【问题讨论】:

  • public B(int a) : base(a) { } 有什么问题?
  • 问题是当我调用类 B 时,例如,我需要将一些实例值的 b 设置为 1 ,我会更新我的问题

标签: c# oop constructor


【解决方案1】:

这样做的唯一方法是重载B 中的构造函数:

public class B : A
{
    public B(int a) : base(a) { }
    public B(int a, int b) : base(a, b) { }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多