new 的用法

 new 修饰符

在用作修饰符时,new 关键字可以显式隐藏从基类继承的成员。隐藏继承的成员时,该成员的派生版本将替换基类版本。虽然可以在不使用 new 修饰符的情况下隐藏成员,但会生成警告。如果使用 new 显式隐藏成员,则会取消此警告,并记录要替换为派生版本这一事实。
若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并使用 new 修饰符修饰该成员。
// cs_modifier_new.cs
// The new modifier.
using System;
public class BaseC 
{
    public static int x = 55;
    public static int y = 22;
}
public class DerivedC : BaseC 
{
    // Hide field 'x'.
    new public static int x = 100;
    static void Main() 
    {
        // Display the new value of x:
        Console.WriteLine(x);
        // Display the hidden value of x:
        Console.WriteLine(BaseC.x);
        // Display the unhidden member y:
        Console.WriteLine(y);
    }
}
 

new 约束

new 约束指定泛型类声明中的任何类型参数都必须有公共的无参数构造函数。当泛型类创建类型的新实例时,将此约束应用于类型参数
class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

new 运算符

用于创建对象和调用构造函数

Class1 o  = new Class1();

还可用于创建匿名类型的实例:

var query = from cust in customers
            select new {Name = cust.Name, Address = cust.PrimaryAddress};

new 运算符还用于调用值类型的默认构造函数

int i = new int();

 

你可能感兴趣的:(new 的用法)