题
什么是 where T : somevalue
意思是?我刚刚看到一些代码说 where T : Attribute
. 。我认为这与泛型有关,但我不确定这意味着什么或它在做什么。
有人知道吗?
解决方案
对类型参数的约束 ,意味着赋予泛型类或方法的类型 T
必须从类 Attribute
例如:
public class Foo<T> :
where T : Attribute
{
public string GetTypeId(T attr) { return attr.TypeId.ToString(); }
// ..
}
Foo<DescriptionAttribute> bar; // OK, DescriptionAttribute inherits Attribute
Foo<int> baz; // Compiler error, int does not inherit Attribute
这很有用,因为它允许泛型类使用 T
类型的对象执行操作,并且知道任何 T
也必须是 >属性代码>。
在上面的例子中, GetTypeId
可以查询 attr
的 TypeId
,因为 TypeId
是一个属性
的属性,并且因为 attr
是 T
,它必须是继承自 Attribute
的类型。
约束也可用于泛型方法,效果相同:
public static void GetTypeId<T>(T attr) where T : Attribute
{
return attr.TypeId.ToString();
}
您可以对类型进行其他限制;来自 MSDN :
其中T:struct
type参数必须是值 类型。除Nullable外的任何值类型 可以指定。
其中T:class
type参数必须是引用 类型;这也适用于任何类, 接口,委托或数组类型。
其中T:new()
type参数必须是public 无参数构造函数。使用时 连同其他约束, 必须指定new()约束 最后。
其中T:&lt; base class name&gt;
必须是或派生类型参数 来自指定的基类。
其中T:&lt; interface name&gt;
type参数必须是或实现的 指定的接口。多 接口约束可以 指定。约束界面 也可以是通用的。
,其中T:U
为T提供的类型参数必须 是或来自论证 供给U.这称为裸体 类型约束。
其他提示
除了其他人所说的之外,您还有以下内容:
- new() - T 必须有默认构造函数
- class - T 必须是引用类型
- struct - T 必须是值类型
这是一种限制用作泛型参数的类型的方法。所以:
where T : SomeType
意味着T必须来自 SomeType 或实现界面 SomeType