泛型类和泛型方法,下面的例子中定义泛型类的原因是什么?

编程入门 行业动态 更新时间:2024-10-25 22:30:25
本文介绍了泛型类和泛型方法,下面的例子中定义泛型类的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 两者之间有什么区别吗?如果我只是定义方法,它是否与定义类型T的类相同。

/ p>

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); } }

解决方案

它是不一样的,但只有当你有一个泛型类型的属性/字段(只有在类本身是泛型时才可以做)或者你有多个方法时,区别只是显而易见的:

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...)

更多推荐

泛型类和泛型方法,下面的例子中定义泛型类的原因是什么?

本文发布于:2023-11-09 10:29:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572140.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:例子   定义   原因   方法   泛型类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!