解决方案
它是不一样的,但只有当你有一个泛型类型的属性/字段(只有在类本身是泛型时才可以做)或者你有多个方法时,区别只是显而易见的:
public class ArrayWrapper< T> { private T []元素; public T get(int index){ return elements [index]; } public void set(int index,T value){ elements [index] = value;没有< T> T []元素字段不会被编译,并且可以在中使用不同的类型。 get()和 set()放在同一个对象上。 指出,你可能不希望在类上使用< T> < T> ,因为它在两个地方都会引入另一个通用类型参数的方法是独立于类的...)
Is there any difference between the two. What would be the reason that I define a generic class of type T.
If I just define the methods does it mean the same as defining the class of Type 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); } }解决方案
It is not the same, but the difference is only evident when you have properties/fields with a generic type (which you can only do when the class itself is generic) or you have multiple methods:
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; } }Without <T> on the class, the T[] elements field will not compile, and it would be possible to use different types in get() and set() on the same object.
(As Lee pointed out, you probably don't want to use <T> on the methods when you have it on the class, as having it in both places would actually introduce another generic type parameter for the method which is independent of the one for the class...)
更多推荐
泛型类和泛型方法,下面的例子中定义泛型类的原因是什么?
发布评论