C# 在定义 subclass 时 :base class 如何工作?
C# how does the :base class work when defining the subclass?
所以我只是想在这里了解这个概念:
场景一
我有一个名为 Person 的基 class,它有一个没有参数的构造函数(即默认构造函数)
这个 class 有 2 个我可以更改的受保护属性(它们是 public)
现在我想创建一个具有一个额外参数的子class(称之为学生),这样我就可以创建一个具有 3 个参数的构造函数(1 + 2 来自基础 class)
如果我创建一个子对象class,我可以传入 3 个参数 - 没问题,这有效(这可能是错误的方法,但它有效)
场景二
我有一个名为 Person 的基 class,现在我有一个带 2 个参数的构造函数,我没有不带参数的默认构造函数。
当我现在创建为其构造函数创建另一个参数的子 class(学生)时。
这个构造函数只有一个参数,我不能像在方案 1
中那样从基础 class 添加第二个和第三个参数
但是我可以通过使用 :base()
link 基础 class 但是我需要传入值而不是参数。
问题
创建学生对象时如何在 :base
class 中输入自定义值。因为我在 link 子 class 构造函数中传递值。
基础class
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
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);
}
但我不知道如何添加我的基地设置的参数class
Student
构造函数需要获取将传递给 Person
基本构造函数的参数。
class Student : Person
{
private int StudentId;
public Student(string name, int age, int studentId)
: base(name, age)
{
StudentId = studentId;
}
}
所以我只是想在这里了解这个概念:
场景一
我有一个名为 Person 的基 class,它有一个没有参数的构造函数(即默认构造函数)
这个 class 有 2 个我可以更改的受保护属性(它们是 public)
现在我想创建一个具有一个额外参数的子class(称之为学生),这样我就可以创建一个具有 3 个参数的构造函数(1 + 2 来自基础 class)
如果我创建一个子对象class,我可以传入 3 个参数 - 没问题,这有效(这可能是错误的方法,但它有效)
场景二
我有一个名为 Person 的基 class,现在我有一个带 2 个参数的构造函数,我没有不带参数的默认构造函数。
当我现在创建为其构造函数创建另一个参数的子 class(学生)时。
这个构造函数只有一个参数,我不能像在方案 1
中那样从基础 class 添加第二个和第三个参数但是我可以通过使用 :base()
link 基础 class 但是我需要传入值而不是参数。
问题
创建学生对象时如何在 :base
class 中输入自定义值。因为我在 link 子 class 构造函数中传递值。
基础class
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
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);
}
但我不知道如何添加我的基地设置的参数class
Student
构造函数需要获取将传递给 Person
基本构造函数的参数。
class Student : Person
{
private int StudentId;
public Student(string name, int age, int studentId)
: base(name, age)
{
StudentId = studentId;
}
}