如何将通用对象作为方法参数传递

3
这可能是一个非常基础的问题,但仍然让我感到困惑(Google也无法帮助);-) 如何将一个通用对象作为参数传递给函数?
例如,我有一个类 CoolGeneric<T> 现在我需要一个方法 DoSomethingWithAGeneric(CoolGeneric g)。这里编译器不断抱怨需要具体类型参数。但是该方法应该适用于所有类型参数!
我该怎么做?谢谢!
2个回答

7
简单来说:
DoSomethingWithAGeneric<T>(CoolGeneric<T> g)

如果该方法在声明了泛型类型的类中:

class MyClass<T> {

    DoSomethingWithAGeneric(CoolGeneric<T> g)


}

3

您需要:

DoSomethingWithAGeneric<T>(CoolGeneric<T> g)

编译器通常会自动检测出T(泛型类型推断),因此调用者通常不需要指定它;也就是说。

CoolGeneric<int> foo = ...
DoSomethingWithAGeneric(foo);

通常情况下,它与以下内容相同:

DoSomethingWithAGeneric<int>(foo);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接