简体   繁体   English

通用类定义中的可变长度类型参数

[英]Variable length type parameters in generic class definition

Is it possible to add variable number of generic parameters in class definition? 是否可以在类定义中添加可变数量的通用参数?

Ex: 例如:

public class Test<E,T,U...>

And the exact number of generic parameters to be defined while building the instance of the object. 以及在构建对象实例时要定义的泛型参数的确切数量。

No, is not possible, what you can do is following: 不可以,您可以执行以下操作:

define the generic BUT allow varargs in the constructor 在构造函数中定义通用BUT allow varargs

public class Deyen<T, G, M> {

    private final T typo;
    private final G typo22;
    private final M[] typo3;

    public Deyen(T typo, G typo22, M... typo3) {
        this.typo = typo;
        this.typo22 = typo22;
        this.typo3 = typo3;
    }
}

explicit defining vararg when defining the class itself is not bringing forward the compiler... 在定义类本身时未显式定义vararg不会带来编译器...

Apparently you want to be able to make Test take multiple parameters of different types in the form of varargs. 显然,您希望能够使Test采用varargs形式的多个不同类型的参数。

VarArgs are actually being passed as an Array but you can't have an array with different types of objects in it. VarArgs实际上是作为数组传递的,但是您不能在其中包含具有不同类型对象的数组。

However, Can't we instead take a single parameter and that parameter type holds each of the individual "parameters" that needs to be used. 但是,我们不能取一个单独的参数,而该参数类型保存需要使用的每个单独的“参数”。

class TypedInstance<T>{
   Class<T> type;
   T instance;
}

Or 要么

Different classes for each set of parameters you want to use. 您要使用的每组参数的不同类。 Then just pass that class as a param. 然后只需将该类作为参数传递即可。

 class MultiTypedInstanceType1<T, R>{
    public R doSomething(T t){ .... }
}

 class MultiTypedInstanceType2<T, R, P>{
    public R doSomething(T t, P p){ .... }
}

In java it seems not possible to define overloads of type signatures, but in C# it is possible probably because of type expansion . 在Java中,似乎不可能定义类型签名的重载,但在C#中, 可能由于类型扩展而可能 Maybe this is an option... 也许这是一个选择...

class Test<A,B> { }
class Test<A> { }

public class Program
{
    public static void Main()
    {
        var one = new Test<string>();
        var two = new Test<string, int>();
    }
}

Here you overload the signature of the type Test to take either one or two type parameters the same way you would do with method overloads. 在这里,您以与方法重载相同的方式重载Test类型的签名以采用一个或两个类型参数。 Here is a fiddle for that 这是一个小提琴

Unfortunately you would have to create several types for all your variants instead of defining it via variable argument lists. 不幸的是,您必须为所有变量创建几种类型,而不是通过变量参数列表进行定义。

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

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