msdn上这样说: [Quote ] where 子句用于指定类型约束,这些约束可以作为泛型声明中定义的类型参数的变量。例如,可以声明一个泛型类 MyGenericClass,这样,类型参数 T 就可以实现 IComparable<T> 接口:public class MyGenericClass<T> where T:IComparable { } 除了接口约束,where 子句还可以包括基类约束,以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。[/Quote]
new 约束(C# 参考) new 约束指定泛型类声明中的任何类型参数都必须有公共的无参数构造函数。当泛型类创建类型的新实例时,将此约束应用于类型参数,如下面的示例所示: class ItemFactory<T> where T : new() { public T GetNewItem() { return new T(); } }
int x = new int(); // 这句话没问题,不会出错。
new()构造函数约束允许开发人员实例化一个泛型类型的对象。 一般情况下,无法创建一个泛型类型参数的实例。然而,new()约束改变了这种情况,要求类型参数必须提供一个无参数的构造函数。 在使用new()约束时,可以通过调用该无参构造函数来创建对象。 基本形式: where T : new()
泛型实现单例模式 public class Singleton<T> where T : new() { public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { internal static readonly T instance = new T(); } } Response.Write(Singleton<Test>.Instance.Time);public class Test { private DateTime _time; public Test() { System.Threading.Thread.Sleep(3000); _time = DateTime.Now; } public string Time { get { return _time.ToString(); } } }
如果没有这个约束,我调用Factory<int>() 他是不是 要返回new int()这不是出错了么
此处new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数
[Quote ]
where 子句用于指定类型约束,这些约束可以作为泛型声明中定义的类型参数的变量。例如,可以声明一个泛型类 MyGenericClass,这样,类型参数 T 就可以实现 IComparable<T> 接口:public class MyGenericClass<T> where T:IComparable { }
除了接口约束,where 子句还可以包括基类约束,以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。[/Quote]
{
public T GetNewItem()
{
return new T();
}
}
int x = new int(); // 这句话没问题,不会出错。
一般情况下,无法创建一个泛型类型参数的实例。然而,new()约束改变了这种情况,要求类型参数必须提供一个无参数的构造函数。
在使用new()约束时,可以通过调用该无参构造函数来创建对象。
基本形式: where T : new()
泛型实现单例模式
public class Singleton<T> where T : new()
{
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
internal static readonly T instance = new T();
}
}
Response.Write(Singleton<Test>.Instance.Time);public class Test
{
private DateTime _time; public Test()
{
System.Threading.Thread.Sleep(3000);
_time = DateTime.Now;
} public string Time
{
get { return _time.ToString(); }
}
}