.net New有几种用法
3种。
1)new 运算符:用于创建对象和调用构造函数。
2)new 修饰符:在用作修饰符时,new 关键字可以显式隐藏从基类继承的成员。
3)new 约束:用于在泛型声明中约束可能用作类型参数的参数的类型。
针对2,在使用一个类继承一个基类,并且写了同样的方法,此时会正常的使用,但是会提示,建议使用new关键字,显示隐藏。
对同一成员同时使用 new 和 override 是错误的做法,因为这两个修饰符的含义互斥。 new 修饰符会用同样的名称创建一个新成员并使原始成员变为隐藏的。 override 修饰符会扩展继承成员的实现。
在不隐藏继承成员的声明中使用 new 修饰符将会生成警告。
针对3,new约束指定泛型类声明中的任何类型参数都必须具有公共的无参数构造函数。
class ClassFour<T> where T : new() { public T GetNewItem() { return new T(); } }
ClassFour<Employee> EmployeeFactory = new ClassFour<Employee>();
////此处编译器会检查Employee是否具有公有的无参构造函数。
//若没有则会有The Employee must have a public parameterless constructor 错误。
Code Practice:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TheWayToUseNew { public class ClassOne { public void PrintName() { Console.WriteLine("Name"); } } public class ClassTwo : ClassOne { new public void PrintName() { Console.WriteLine("NameTwo"); } } public class ClassThree : ClassOne { public void PrintName() { Console.WriteLine("NameThree"); } } class ClassFour<T> where T : new() { public T GetNewItem() { return new T(); } } public class Employee { private string name; private int id; public Employee() { name = "Temp"; id = 0; } public Employee(string s, int i) { name = s; id = i; } public string Name { get { return name; } set { name = value; } } public int ID { get { return id; } set { id = value; } } } class Program { static void Main(string[] args) { // first way for instantiation ClassOne classOne = new ClassOne(); classOne.PrintName(); // second way to hide base class method ClassTwo classTwo = new ClassTwo(); classTwo.PrintName(); // third way to not hide base class method ClassThree classThree = new ClassThree(); classThree.PrintName(); // fourth way to constraint genericity ClassFour<Employee> EmployeeFactory = new ClassFour<Employee>(); ////此处编译器会检查Employee是否具有公有的无参构造函数。 //若没有则会有The Employee must have a public parameterless constructor 错误。 Console.WriteLine("{0}'ID is {1}.", EmployeeFactory.GetNewItem().Name, EmployeeFactory.GetNewItem().ID); Console.ReadLine(); } } } -----------------------------------
联系方式
公众号_DotNet微说.jpg
©著作权归作者所有:来自51CTO博客作者懒家伙z的原创作品,请联系作者获取转载授权,否则将追究法律责任
.net New有几种用法
https://blog.51cto.com/u_11071029/5090459
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2021-08-12 Github上git commit 提交注释的规范