简体   繁体   English

通用和方法

[英]Generic and method

Why do I have to do like this? 为什么我要这样做?

public <T> void myMethod(MyClass<T> value){

}

Why do I have to mention <T> twice? 为什么我要提两次<T>

The first <T> declares your method as having a generic parameter. 第一个<T>将您的方法声明为具有泛型参数。

The second <T> specified the value of the generic parameter for the MyClass<> class. 第二个<T>指定了MyClass<>类的泛型参数的值。 (just like MyClass<string> ) (就像MyClass<string>

the first <T> declares that you are using a templated method. 第一个<T>声明您正在使用模板化方法。 It is just as proper to say the following: 说出以下内容是恰当的:

public void myMethod(MyClass<?> value){

}

You can also declare the generic parameter on the class level like so: 您还可以在类级别声明泛型参数,如下所示:

public class MyClass<T> {

    public void myMethod(MyClass<T> value){
    }
}

The outer <T> says 'this is a generic method' and also gives you the chance to place bounds on T, for example T extends Comparable<T>. 外部<T>表示“这是一种通用方法”,并且还为您提供了在T上放置边界的机会,例如T扩展了Comparable <T>。 You wouldn't want to be repeating all that for every parameter that used T. 您不希望为使用T的每个参数重复所有这些。

实际上是第一个限定有在你的函数被使用的通用类和第二MyClass<T>值表示,所述类型类它的TList<String>其中String可以是你的T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM