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

 

posted @ 2021-03-31 18:00  shine声  阅读(1353)  评论(0编辑  收藏  举报