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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM