有没有人能告诉我
public T Get<T>(int id)
和
public T Get(int id)
发布于 2012-06-25 11:31:33
比较:
class First
{
public T Get<T>(int id) // T is declared in the method scope
{
}
}
和
class Second<T>
{
public T Get(int id) // T is declared in the class scope
{
}
}
还有第三种情况:
class Third<U>
{
public T Get<T>(int id) // T is declared in the method scope when class scope has another generic argument declared
{
}
}
发布于 2012-06-25 11:42:35
不同之处在于,如果这是以前没有定义过T的时候,则使用第一种类型的声明。即。
public class MyClass
{
public T Get<T>(int id);
}
第二次是在类级别已经定义了T的时候。即。
public class MyClass<T>
{
public T Get(int id);
}
在这种情况下,您还可以使用第一种类型的声明-这实际上是速记。在效果上没有区别。
编辑事实上,第二个声明只要求T在作用域中,另一个示例是嵌套类,如...
public class MyClass<T>
{
public class NestedClass
{
public T Get(int i);
}
}
发布于 2012-06-25 11:42:02
在代码中使用它们之前,请先阅读有关Generics的内容。
https://stackoverflow.com/questions/11188487
复制