C#关键字-运算符关键字-new

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

new运算符:用于创建对象和调用构造函数。

new修饰符:用于向基类成员隐藏继承成员。

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

new运算符

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

Class1 obj = new Class1();

2.用于创建匿名类型的实例。

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

3.用于调用值类型的默认构造函数。

//i 初始化为 0,它是 int 类型的默认值。 该语句的效果等同于:int i = 0;
int i = new int();

注意:为结构声明默认的构造函数是错误的,因为每一个值类型都隐式具有一个公共的默认构造函数。不能重载new运算符
   如果new运算符分配内存失败,将引发异常OutOfMemoryException。

 

new修饰符

在用作修饰符时,new关键字可以显式隐藏从基类继承的成员。隐藏继承的成员时,该成员的派生版本将替换基类版本。虽然可以在不使用new修饰符的情况下隐藏成员,但会生成警告。如果使用new显示隐藏成员,则会取消此名警告,并记录要替换为派生版本这一事实。

对同一成员同时使用new和override是错误的做法,因为这两个修饰符的含义互斥。new修饰符会用同样的名称创建一个新成员并使原始成员变为隐藏的。override修饰符会扩展继承成员的实现。

View Code
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);
    }
}
/*
Output:
100
55
22
*/

 

new约束(有关更多信息,请参见 类型参数的约束(C# 编程指南))

new约束指定泛型类声明中的任何类型参数都必须有公共的无参数构造函数。如果要使用new约束,则该类型不能为抽象类型。

1.当泛型类创建类型的新实例,请将new约束应用于类型参数。

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

2.当与其他约束一起使用时,new()约束必须最后指定。

public class ItemFactory2<T> where T : IComparable, new()
{
    \\... ...
}

 

 

posted on 2012-05-03 14:54  YeChun  阅读(1187)  评论(0编辑  收藏  举报

导航