C# new 关键字用法

试题回答参考思路:

一,用法总结:
在c#中,new关键字可用作运算符,声明修饰符,约束。
1)new运算符:new 运算符创建类型的新实例,调用构造函数(如果继承了基类,同时会调用基类的构造函数)。
2)new声明修饰符:
2.1)在用作声明修饰符时,new 关键字可以显式隐藏从基类继承的成员。派生类成员变量被new关键字修饰以后,只能被派生类调用。如果希望重写基类成员变量/方法,可以使用virtual/override修饰关键字。
2.2)派生类如果定义了和基类同名的成员变量/方法,同样会隐藏基类的同名变量/方法,但编译器会警告。 如果使用 new 来修饰,将不显示此警告。
3)new约束:new 约束指定泛型类或方法声明中的类型实参必须有公共的无参数构造函数。 若要使用 new 约束,则该类型不能为抽象类型。

二,测试代码:
本代码基于以下条件进行测试:
操作系统:Windows 11 专业版
开发工具:Microsoft Visual Studio Enterprise 2022 (64 位) - 版本 17.7.3
项目框架:.NET 7.0
1)new 运算符:(参考github中项目:01.new运算符)
//这是 AnimalBase.cs 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01.new运算符
{
internal class AnimalBase
{
public AnimalBase()
{
Console.WriteLine("我是AnimalBase的构造函数。");
}
}
}

//这是 Dog.cs 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01.new运算符
{
internal class Dog : AnimalBase
{
public Dog()
{
Console.WriteLine("我是Dog的构造函数。");
}
}
}

//这是 Program.cs 类
using _01.new运算符;
Console.WriteLine("1)new 运算符:调用构造函数");
AnimalBase animalBase = new AnimalBase();
Console.WriteLine("\n1)new 运算符:继承了基类,调用了基类和自己的构造函数");
AnimalBase animalBase1 = new Dog();
Dog dog = new Dog();

posted @ 2024-03-04 20:54  平常xin  阅读(21)  评论(0编辑  收藏  举报