首页 新闻 会员 周边

T 是个什么东西?

0
悬赏园豆:10 [已解决问题] 解决于 2010-10-28 15:40

 求教个问题。

http://www.cnblogs.com/GoodHelper/archive/2010/10/16/SpringNetFramework_Step2.html

 这边有个接口这样定义

 public interface IGenericManager<T> where T : class

这边的T是个什么东西?如何使用?

clound的主页 clound | 菜鸟二级 | 园豆:481
提问于:2010-10-28 15:11
< >
分享
最佳答案
0

泛型,可以代表任何类型,在这里只能是类,不能是接口,因为where T : class

收获园豆:3
wang_yb | 老鸟四级 |园豆:4891 | 2010-10-28 15:21
非常感谢
clound | 园豆:481 (菜鸟二级) | 2010-10-28 15:39
其他回答(1)
0

这是一个泛形接口,过泛型可以定义类型安全的数据结构,而无须使用实际的数据类型。

例: // Declare the generic class
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}

where 关键字:

派生约束

在 C# 2.0 中,可以使用 where 保留关键字来定义约束。在一般类型参数中使用 where 关键字,后面跟一个派生冒号,以指示编译器该一般类型参数实现了特定接口。

T:结构

类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。有关更多信息,请参见使用可空类型(C# 编程指南)。

T:类

类型参数必须是引用类型,包括任何类、接口、委托或数组类型。

T:new()

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

T:<基类名>

类型参数必须是指定的基类或派生自指定的基类。

T:<接口名称>

类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。

T:U

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

问题里面 where T : class 表示为T指定的具体类型必须是一个class,而不可以是interface,struct等

具体相关知识可以查看MSDN 中关于C#泛形的说明,也可查看《C#与.NET 3.5高级程序设计》 第10章 集合与泛型

收获园豆:7
SharpDeveloper | 园豆:227 (菜鸟二级) | 2010-10-28 15:33
哇,这个太详细了,非常感谢。
支持(0) 反对(0) clound | 园豆:481 (菜鸟二级) | 2010-10-28 15:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册