C#中new的三种用法

在 C# 中,new 关键字可用作运算符、修饰符或约束。
1)new 运算符:用于创建对象和调用构造函数。
2)new 修饰符:在用作修饰符时,new 关键字可以显式隐藏从基类继承的成员。
3)new 约束:用于在泛型声明中约束可能用作类型参数的参数的类型
 
复制代码
public class Program: BaseClass
    {
        new public class Test//2、new修饰符 显式隐藏从基类继承的成员
        {
            public int x = 2;
            public int y = 20;
            public int z = 40;
        }

        static void Main(string[] args)
        {
            var c1 = new Test();//1、new操作符 创建对象和调用构造函数
            var c2 = new BaseClass.Test();
            Console.WriteLine(c1.x);//2
            Console.WriteLine(c2.y);//10
            Console.ReadKey();
        }
    }

    public class BaseClass
    {
        public class Test
        {
           public int x = 0;
           public int y = 10;
        }   
    }
复制代码

new约束指定泛型类声明中的任何类型参数都必须具有公共的无参数构造函数

复制代码
using System;
using System.Collections.Generic;
 
namespace ConsoleApplication2
{
    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 ItemFactory<T> where T : new()
    {
        public T GetNewItem()
        {
            return new T();
        }
    }
 
    public class Test
    {
        public static void Main()
        {
            ItemFactory<Employee> EmployeeFactory = new ItemFactory<Employee>();
            ////此处编译器会检查Employee是否具有公有的无参构造函数。
            //若没有则会有The Employee must have a public parameterless constructor 错误。
            Console.WriteLine("{0}'ID is {1}.", EmployeeFactory.GetNewItem().Name, EmployeeFactory.GetNewItem().ID);
        }
    }
}
复制代码

 

posted @   Homegu  阅读(10316)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
你的浏览器不支持canvasr
点击右上角即可分享
微信分享提示