Q&A-4-C# 中new的3 种用法

8 篇文章 0 订阅

在 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;
        }   
    }

 

3、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);
        }
    }
}


 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值