C# 面向对象的new关键字的使用

mac2022-06-30  31

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplicationTest { class Program { static void Main(string[] args) { Student s = new Student("'zhangsan",19,1); //父类中的person say hello 没有输出,原因是隐藏了父类的方法 //如果想有意隐藏父类的同名方法 使用关键字new s.SayHello(); //student say hello Console.ReadKey(); } } public class Person { public string Name { get; set; } public int Age { get; set; } //父类构造函数 public Person(string name,int age) { this.Name = name; this.Age = age; } public void SayHello() { Console.WriteLine("person say hello"); } } public class Student:Person { public int Id { get; set; } //子类构造函数 //关键字base的使用:调用父类的构造函数 public Student(string name,int age,int id):base(name,age) { this.Id = id; } public new void SayHello() { Console.WriteLine("student say hello"); } } }

PS:new关键字

1)创建对象

2)隐藏从父类那里继承过来的同名成员

隐藏的后果就是子类调用不到父类的成员。

转载于:https://www.cnblogs.com/zoro-zero/p/4057945.html

最新回复(0)