New 关键词的三种用法 C#
(2)new 修饰符 用于隐藏基类成员的继承成员。
(3)new 约束 用于在泛型声明中约束可能用作类型参数的参数的类型。
new 运算符
1.用于创建对象和调用构造函数
例:Class_Test MyClass = new Class_Test();
2.也用于为值类型调用默认的构造函数
例:int myInt = new int();
myInt 初始化为 0,它是 int 类型的默认值。该语句的效果等同于:int myInt = 0;
3.不能重载 new 运算符。
4.如果 new 运算符分配内存失败,则它将引发 OutOfMemoryException 异常。
new 修饰符
使用 new 修饰符显式隐藏从基类继承的成员。若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并用 new 修饰符修饰它。
请看下面的类:
2
3 {
4
5 public int x;
6
7 public void Invoke() {}
8
9 }
10
在派生类中用 Invoke 名称声明成员会隐藏基类中的 Invoke 方法,即:
2
3 {
4
5 new public void Invoke() {}
6
7 }
8
但是,因为字段 x 不是通过类似名隐藏的,所以不会影响该字段。
通过继承隐藏名称采用下列形式之一:
1.引入类或结构中的常数、指定、属性或类型隐藏具有相同名称的所有基类成员。
2.引入类或结构中的方法隐藏基类中具有相同名称的属性、字段和类型。同时也隐藏具有相同签名的所有基类方法。
3.引入类或结构中的索引器将隐藏具有相同名称的所有基类索引器。
4.在同一成员上同时使用 new 和 override 是错误的。
注意:在不隐藏继承成员的声明中使用 new 修饰符将生成警告。
示例
在该例中,基类 MyBaseC 和派生类 MyDerivedC 使用相同的字段名 x,从而隐藏了继承字段的值。该例说明了 new 修饰符的使用。同时也说明了如何使用完全限定名访问基类的隐藏成员。
2
3 public class MyBaseC
4
5 {
6
7 public static int x = 55;
8
9 public static int y = 22;
10
11 }
12
13
14
15 public class MyDerivedC : MyBaseC
16
17 {
18
19 new public static int x = 100; // Name hiding
20
21 public static void Main()
22
23 {
24
25 // Display the overlapping value of x:
26
27 Console.WriteLine(x);
28
29
30
31 // Access the hidden value of x:
32
33 Console.WriteLine(MyBaseC.x);
34
35
36
37 // Display the unhidden member y:
38
39 Console.WriteLine(y);
40
41 }
42
43 }
44
输出
100
55
22
如果移除 new 修饰符,程序将继续编译和运行,但您会收到以下警告:
The keyword new is required on 'MyDerivedC.x' because it hides inherited member 'MyBaseC.x'.
如果嵌套类型正在隐藏另一种类型,如下例所示,也可以使用 new 修饰符修改此嵌套类型。
示例
在该例中,嵌套类 MyClass 隐藏了基类中具有相同名称的类。该例不仅说明了如何使用完全限定名访问隐藏类成员,同时也说明了如何使用 new 修饰符消除警告消息。
2
3 public class MyBaseC
4
5 {
6
7 public class MyClass
8
9 {
10
11 public int x = 200;
12
13 public int y;
14
15 }
16
17 }
18
19
20
21 public class MyDerivedC : MyBaseC
22
23 {
24
25 new public class MyClass // nested type hiding the base type members
26
27 {
28
29 public int x = 100;
30
31 public int y;
32
33 public int z;
34
35 }
36
37
38
39 public static void Main()
40
41 {
42
43 // Creating object from the overlapping class:
44
45 MyClass S1 = new MyClass();
46
47
48
49 // Creating object from the hidden class:
50
51 MyBaseC.MyClass S2 = new MyBaseC.MyClass();
52
53
54
55 Console.WriteLine(S1.x);
56
57 Console.WriteLine(S2.x);
58
59 }
60
61 }
62
输出
100
200
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)