【发布时间】:2018-11-27 18:27:52
【问题描述】:
这个很难解释,但我会尽量保持简单。 假设我有一个名为 Car 的对象,并且我有一个接收以下内容的函数:
public void foo(Class<Car> type){
// I want to create a list of this type, do something like this
List<type> list = new List<type>
// I know its not the way to do it but is there any way to do something like this
长话短说,我想创建一个汽车列表 是否可以给定 Class 对象?
【问题讨论】:
-
是的,但您为什么要这样做?你到底想完成什么?
-
这只是一个例子,我不想开始解释我项目中发生的一切,因为它会很长。
-
所以
Class<Car>代表Car类。如果您想要汽车列表,您已经有了已知类型:List<Car>,如果您想要汽车类别列表 (???),您可以使用List<Class<Car>>,如果不知道它是 @987654326 @ 并想要一个泛型类型,请查看泛型方法。您需要提供更多关于您正在尝试做的事情的背景信息。 -
是的,关键是我不知道它是一辆车,抱歉没有提到。
-
您将需要提炼项目中正在发生的事情。编写这样的代码经常因为不可维护性而受到反对。