new关键字有如下几种用法:
1. 作为运算符
1)Object obj= new Object();
new 运算符不能重载,如果在初始化对象时失败,会抛出OutOfMemoryException 异常。
2. 作为修饰符
使用 new 修饰符显式隐藏从基类继承的成员。若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并用 new 修饰符修饰它。
Sample:
BASE CLASS:
public class Base
{
private string str1;
public string Str1
{
get
{
return str1;
}
set
{
str1 = value;
}
}
public Base(string str1)
{
this.str1 = str1;
}
public string Method1()
{
return this.str1;
}
}
Inheriate Class:
public class Inheritate:Base
{
private string str2;
public string Str2
{
set { this.str2 = value; }
get { return this.str2; }
}
public Inheritate(string str2, string str1)
: base(str1)
{
this.str2 = str2;
}
public new string Method1()
{
return this.Str1 + "" + this.Str2;
}
}
New 不仅可以放在成员变量,成员函数上,也可以放在类上。
3. 用于泛型类型约束 new 约束
new 约束指定泛型类声明中的任何类型参数都必须有公共的无参数构造函数。 如果要使用 new 约束,则该类型不能为抽象类型。
class ItemFactory<T> where T : new() { public T GetNewItem() { return new T(); } }