"哪里T:somevalue"是什么意思?

mik*_*kpy 11 c# generics constraints

什么where T : somevalue意思?我刚刚看到一些代码说where T : Attribute.我认为这与泛型有关,但我不确定这意味着什么或它在做什么.

有人知道吗?

Dan*_*ant 28

它是对类型参数约束,这意味着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
Run Code Online (Sandbox Code Playgroud)

这很有用,因为它允许泛型类使用类型的对象执行操作T,并且知道任何T必须也是的Attribute.

在上面的例子中,可以GetTypeId查询TypeIdof,attr因为TypeId是a的属性Attribute,因为它attr是一个T必须是继承自的类型Attribute.

约束也可以用于泛型方法,具有相同的效果:

public static void GetTypeId<T>(T attr) where T : Attribute
{
   return attr.TypeId.ToString();
}
Run Code Online (Sandbox Code Playgroud)

您可以对类型进行其他限制; 来自MSDN:

where T: struct

type参数必须是值类型.可以指定除Nullable之外的任何值类型.

where T : class

type参数必须是引用类型; 这也适用于任何类,接口,委托或数组类型.

where T : new()

type参数必须具有公共无参数构造函数.与其他约束一起使用时,必须最后指定new()约束.

where T : <base class name>

type参数必须是或从指定的基类派生.

where T : <interface name>

type参数必须是或实现指定的接口.可以指定多个接口约束.约束接口也可以是通用的.

where T : U

为T提供的类型参数必须是或者从为U提供的参数派生.这称为裸类型约束.


lep*_*pie 5

此外,其他人说,你也有以下内容:

  • new() - T必须有默认构造函数
  • class - T必须是引用类型
  • struct - T必须是值类型