C#语法看不懂!

来源:百度知道 编辑:UC知道 时间:2024/05/25 21:26:41
public sealed class Singleton<T> where T : new()
谁能解释一下这句代码是什么意思?
原文如下:
/// <summary>
/// Singleton泛型类
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class Singleton<T> where T : new() //在这儿!
{
private static T instance = new T();

private static object lockHelper = new object();

/// <summary>
/// 构造函数
/// </summary>
private Singleton()
{ }

/// <summary>
/// 获取实例
/// </summary>
/// <param name="value"></param>
public static T GetInstance()
{
if (instance == null)
{
lock (lockHelper)
{
if (instance == null)

where 子句用于指定类型约束,这些约束可以作为泛型声明中定义的类型参数的变量。例如,可以声明一个泛型类 MyGenericClass,这样,类型参数 T 就可以实现 IComparable<T> 接口:

复制代码
public class MyGenericClass<T> where T:IComparable { }

除了接口约束,where 子句还可以包括基类约束,以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。

// cs_where.cs
// compile with: /target:library
using System;

class MyClassy<T, U>
where T : class
where U : struct
{
}

where 子句还可以包括构造函数约束。可以使用 new 运算符创建类型参数的实例;但类型参数为此必须受构造函数约束 new() 的约束。new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数。例如:

// cs_where_2.cs
// compile with: /target:library
using System;
public class MyGenericClass <T> where T: IComparable, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}

new() 约束出现在 where 子句的最后。

对于多个类型参数,每个类型参数都使用一个 where 子句,例如:

// cs_wher