C#中泛型约束(where)是什么?
2017-08-02 17:22
423 查看
泛型约束: 确保泛型类使用的参数是提供特定方法的类型。
详见:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/generics/generic-classes
约束 | 说明 |
T:结构 | 类型参数必须是值类型。 |
T:类 | 类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。 |
T:new() | 类型参数必须具有无参数的公共构造函数。 当与其他约束一起使用时,new() 约束必须最后指定。 |
T:<基类名> | 类型参数必须是指定的基类或派生自指定的基类。 |
T:<接口名称> | 类型参数必须是指定的接口或实现指定的接口。 可以指定多个接口约束。 约束接口也可以是泛型的。 |
T:U | 为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。 |
public class BaseAccess<T> where T : Access
{
}
T约定:T只能传入接口的本身和实现了此接口的类
public class BaseAccess<T> where T : IAggregateRoot
{
}
引用类型约束演示
public class BaseAccess<T> where T : class
{
}
值类型约束演示
public class BaseAccess<T> where T : struct
{
}
构造器约束
public class BaseAccess<T> where T : new()
{
MongoContextAdapter _context;
public BaseAccess(MongoContextAdapter context)
{
this._context = context;
}
}
一个类型占位符有两个约束 必须是引用类型,必须提供构造函数
public class BaseAccess<T> where T : class,new()
{
}
K必须约定是一个引用类型
V必须约定是一个值类型
public class BaseAccess<K, V>
where K : class,new()
where V : struct
{
}
/// 泛型参数K必须继承V K,V必须是引用类型,必须提供构造函数
public class BaseAccess<K, V>
where K : V
where K : class,new()
where V : class,new()
{
}
T约定:只能是Access类型或者Access的子类型
public class BaseAccess<T> where T : Access
{
}
T约定:T只能传入接口的本身和实现了此接口的类
public class BaseAccess<T> where T : IAggregateRoot
{
}
引用类型约束演示
public class BaseAccess<T> where T : class
{
}
值类型约束演示
public class BaseAccess<T> where T : struct
{
}
构造器约束
public class BaseAccess<T> where T : new()
{
MongoContextAdapter _context;
public BaseAccess(MongoContextAdapter context)
{
this._context = context;
}
}
一个类型占位符有两个约束 必须是引用类型,必须提供构造函数
public class BaseAccess<T> where T : class,new()
{
}
K必须约定是一个引用类型
V必须约定是一个值类型
public class BaseAccess<K, V>
where K : class,new()
where V : struct
{
}
/// 泛型参数K必须继承V K,V必须是引用类型,必须提供构造函数
public class BaseAccess<K, V>
where K : V
where K : class,new()
where V : class,new()
{
}
相关文章推荐
- C# 泛型类型约束 where
- C# 泛型 WHERE 约束
- C#中的where泛型约束中的new()使用(转)
- C#中的where泛型约束
- C#中的where泛型约束
- C# 泛型方法Where 约束
- C# 泛型约束 xxx<T> Where T:约束(一)
- 【C#】C#关键字-where(泛型类型约束)
- c#泛型类型的约束条件where
- C#中的where泛型约束中的new()
- C#中的where泛型约束中的new()构造函数约束
- C#中的where泛型约束【转】
- c# 泛型类型参数T的约束where
- C#中的where泛型约束
- c#中的WHERE语句 ——where(泛型类型约束)
- C#中的where泛型约束中的new()构造函数约束
- C# 泛型约束 xxx Where T:约束(二)
- 关于C#中泛型类型参数约束(where T : class)
- c# where(泛型类型约束)
- 关于C#中泛型类型参数约束(where T : class)