C# :base class work when defining the subclass? 怎么办

标签 c# parameters subclass

所以我只是想在这里了解这个概念:

场景一

我有一个名为 Person 的基类,它有一个没有参数的构造函数(即默认构造函数)

这个类有 2 个我可以更改的 protected 属性(它们是公共(public)的)

现在我想创建一个具有一个额外参数的子类(称之为学生),这样我就可以创建一个具有 3 个参数(1 + 2 来自基类)的构造函数

如果我创建一个子类的对象,我可以传入 3 个参数 - 没问题,这可行(这可能是错误的方法,但它可行)

场景二

我有一个名为 Person 的基类,现在我有一个带 2 个参数的构造函数,我没有不带参数的默认构造函数。

当我现在创建为其构造函数创建另一个参数的子类(学生)时。

这个构造函数只有一个参数,我不能像在场景 1 中那样从基类添加第二个和第三个参数

不过,我可以使用 :base() 链接基类,但我需要传入值而不是参数。

问题

创建学生对象时如何在 :base 类中添加自定义值。因为我在子类构造函数中链接它时传入了值。

基类

class Person
{
    protected string Name;
    protected int Age;

    //public Person1(){}

    public Person(string _name, int _age)
    {
        Name = _name;
        Age = _age;
    }

    public void SayHello()
    {
        Console.WriteLine("Helllo World!");
        Console.WriteLine($"My name is {Name} and I am {Age} years old");
    }
}

子类

class Student : Person1
{
    private int StudentId;

    //I was hoping to put in new parameters in the base ()
    public Student(int _studentId) : base ("", 00)
    {
        //_name and _age do not exist
        //Name = _name;
        //Age = _age;
        StudentId = _studentId;
    }
}

Program.cs

    static void Main(string[] args)
    {
        var p1 = new Person1("John", 45);
        p1.SayHello();


        var student1 = new Student(123456);
    }

但是我不知道如何添加在我的基类中设置的参数

最佳答案

Student 构造函数需要获取将传递给 Person 基本构造函数的参数。

class Student : Person
{
    private int StudentId;

    public Student(string name, int age, int studentId)
        : base(name, age)
    {
        StudentId = studentId;
    }
}

关于C# :base class work when defining the subclass? 怎么办,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43245799/

相关文章:

delphi - `const` 的使用是教条性的还是理性的?

map - 当发出配置中定义的类的子类作为输出时,Hadoop Map 输出 IOException

java - 使用instanceof或public方法获取实例

c# - 如何将图像连同 DPI 信息一起保存到剪贴板?

c# - 为什么下面的泛型方法调用不需要类型?

c - 如何使函数使用不确定数量的参数和va_list组合参数?

c# - 未知类型的动态,这还能如何实现?

java - 基于逻辑构造对象类型——这可以做到吗?

c# - 字典 : An item with the same key has already been added

c# - 并发 AJAX 和标准表单 POST 后连接重置