1-new
1) 创建对象
在堆中开辟空间(因为引用类型就是在堆中)
在开辟的堆空间中创建对象
调用对象的构造函数
2)隐藏父类的成员
3)代码展示
Person.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace _04三个关键字
{
class Person
{
public void SayHi()
{
Console.WriteLine("世界和平");
}
}
class Student:Person
{
public void SayHi()
{
Console.WriteLine("学海无涯");
}
}
}
Program.cs
using _04三个关键字;
using System;
namespace _04三个关键字
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
}
}
}
效果展示
报错:
原因:如果子类的成员名称跟父类成员名称一样的话,此时,子类成员就会把父类成员隐藏,但是隐藏不彻底,子类就无法访问到父类,
但 是会报错
解决办法:将子类成员添加new
修改如下
using System;
using System.Collections.Generic;
using System.Text;
namespace _04三个关键字
{
class Person
{
public void SayHi()
{
Console.WriteLine("世界和平");
}
}
class Student:Person
{
public **new** void SayHi()
{
Console.WriteLine("学海无涯");
}
}
}
编译成功
2-this 关键字
1)代表当前类的对象
2)代码展示
Person.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace _04三个关键字
{
class Person
{
public void SayHi()
{
Console.WriteLine("世界和平");
}
}
class Student:Person
{
public new void SayHi()
{
Console.WriteLine("学海无涯");
}
public string Name { get; set; }
public void Test()
{
string Name = "王者农药";
Console.WriteLine("我的名字叫{0}"+Name);
}
}
}
Program.cs
using _04三个关键字;
using System;
namespace _04三个关键字
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.Name = "王者荣耀";
s.Test();
Console.ReadKey();
}
}
}
效果展示
如果将上面Person.cs的代码改为
using System;
using System.Collections.Generic;
using System.Text;
namespace _04三个关键字
{
class Person
{
public void SayHi()
{
Console.WriteLine("世界和平");
}
}
class Student:Person
{
public new void SayHi()
{
Console.WriteLine("学海无涯");
}
public string Name { get; set; }
public void Test()
{
string Name = "王者农药";
Console.WriteLine("我的名字叫{0}"+**this**.Name);
}
}
}
效果展示:
原因分析:1)this是指对象
2) 局部变量的优先级大于成员变量,方法中变量为局部变量,而方法为成员变量
因此string Name=“王者农药”; 优先级要大于s.Test(),因此不加this关键字时候,会出现第一种情况
3)加上this关键字时候,就会第二种情况,因为this是指引用,前面new了一个student为s,s.Name为王者荣耀,因此输出
王者荣耀
3-base