zoukankan      html  css  js  c++  java
  • C# new关键字的使用

    一.前言

      在C#中,new关键字可以用来作运算符、约束、修饰符。

    二.用法

    1.new运算符

      用于创建对象和调用构造函数。这个new的使用是语法基础,没什么需要了解的,用过几遍都知道。

    public class A
    {
        public A()
        {
            Console.WriteLine("初始构造函数");
        }
        public A(string a)
        {
            Console.WriteLine("带参构造函数,参数:" + a);
        }
    }
    
    //调用
    public static void Main(string[] args)
    {
        A a = new A();
        A a2 = new A("233");
    }

    2.new约束

      用在泛型声明中约束可能用作类型参数的参数的类型。

    public class A
    {
    
    }
    
    public class Item<T> where T : new()
    {
        public T GetNewItem()
        {
            return new T();
        }
    }
    
    //调用
    public static void Main(string[] args)
    {
        Item<A> item = new Item<A>();
    }

      new()在这里是限制泛型的参数必须是一个类,且带无参的构造函数。

    3.new修饰符

      可以显示隐藏从基类继承的成员。用于在派生类和基类中相同签名的属性或方法。不使用new关键字也会隐藏,但编译器会提示警报。

    public class A
    {
        public int ID = 1;
    
        public void Func()
        {
            Console.WriteLine("A");
        }
    }
    
    public class B : A
    {
        public new int ID = 2;
    
        public new void Func()
        {
            Console.WriteLine("B");
        }
    }
  • 相关阅读:
    jQuery代码优化的9种方法
    关于javascript代码优化的8点建议
    javascript编码标准
    前端学算法之算法复杂度
    前端学算法之算法模式
    前端学算法之搜索算法
    前端学算法之排序算法
    前端学数据结构之图
    前端学数据结构之树
    前端学数据结构之字典和散列表
  • 原文地址:https://www.cnblogs.com/shadoll/p/14504740.html
Copyright © 2011-2022 走看看