两者之间有什么区别吗?我定义T类通用类的原因是什么。
如果我只是定义方法,那就意味着定义类型T的类。
void Main()
{
Test1<int> x = new Test1<int>();
x.Test1Method(1);
Test2 x1 = new Test2();
x1.Test2Method(1);
}
public class Test1<T>
{
public void Test1Method<T>(T x)
{
Console.WriteLine(x);
}
}
public class Test2
{
public void Test2Method<T>(T x)
{
Console.WriteLine(x);
}
}
答案 0 :(得分:1)
它不一样,但只有当您拥有具有泛型类型的属性/字段(您只能在类本身是通用时才能执行)或者您有多种方法时,差异才会明显:
public class ArrayWrapper<T> {
private T[] elements;
public T get(int index) {
return elements[index];
}
public void set(int index, T value) {
elements[index] = value;
}
}
在课程中没有<T>
,T[] elements
字段将无法编译,并且可以在同一对象的get()
和set()
中使用不同的类型。
(正如李指出的那样,你可能不希望在类上使用<T>
时,因为在两个地方都有它会为这个方法实际引入另一个泛型类型参数独立于班级......)
答案 1 :(得分:1)
在课程Test1
中,在课程级别定义的T
与T
方法中定义的Test1Method
不同。这使得班级T
无用。
您可以像这样使用Test1
:
Test1<string> x = new Test1<string>();
x.Test1Method(1);
在这种情况下,第一个T
为string
,第二个T
为int。
就像现在一样,Test1
与Test2
没有区别。
如果你这样定义Test1
会有所不同:
public class Test1<T>
{
public void Test1Method(T x)
{
Console.WriteLine(x);
}
}
请注意,此更改后Test1Method
的参数不具有通用T
。现在,这个类与Test2
的不同之处在于Test1
在对象构造时指定T
,而在Test2
中,每次调用时都可以使用不同的T
Test2Method
。
以下是如何使用这两个类的示例(在我介绍的更改之后):
Test1<int> x = new Test1<int>();
x.Test1Method(1); //valid
x.Test1Method(2); //valid
x.Test1Method("str"); //invalid
Test2 x1 = new Test2();
x1.Test2Method(1); //valid
x1.Test2Method("str"); //valid