简体   繁体   English

使用多个泛型类型调用泛型方法而不指定每个泛型类型

[英]Call generic Method with multiple generic Types without specifying every single generic Type

So what I have is a generic Method with multiple generic types.所以我拥有的是一个具有多种泛型类型的泛型方法。

Now I'd like to call this Method this way (using the types of a and b and just specifying the return type):现在我想这样调用这个方法(使用 a 和 b 的类型并只指定返回类型):

class Example
{

    T1 GenericMethod<T1, T2, T3>(T2 parameter1, T3 parameter2)

    {
        T1 returnValue = default(T1);

        // ... Do something with returnType, parameter1 and parameter2

        return returnValue;
    }

    void AccessGenericMethod()
    {
        var a = new Foo1();
        var b = new Foo2();
        var result = GenericMethod<ReturnType>(a, b); // doesn't work
    }
}

And i would like to avoid to call GenericMethod this way我想避免以这种方式调用GenericMethod

var result GenericMethod<ReturnType, Foo1, Foo2>(a, b);

In C#, there is no partial type inference: You must either specify all or none of the generic arguments, but the latter only works if the compiler is able to infer all types from context.在 C# 中,没有部分类型推断:您必须指定全部或不指定泛型参数,但后者仅在编译器能够从上下文推断所有类型时才有效。 Return types cannot be infered (except for some special cases such as lambdas), so what you want to do is not possible.无法推断返回类型(除了一些特殊情况,如 lambdas),所以你想要做的事情是不可能的。

Two workarounds:两种解决方法:

A: Move T1 from the method to the class A:将T1从方法移到类

class Example<T1>
{
    T1 GenericMethod<T2, T3>(T2 parameter1, T3 parameter2)

B: Replace T2 and T3 by object B:用object替换T2T3

class Example
{
    T1 GenericMethod<T1>(object parameter1, object parameter2)

I found a solution我找到了解决方案

class Example
{
    T1 GenericMethod<T1, T2, T3>(T2 parameter1, T3 parameter2, out T1 returnValue)
    {
        returnValue = default(T1);

        // ... Do something with returnType, parameter1 and parameter2

        return returnValue = new T1();
    }

    void AccessGenericMethod()
    {
        var a = new Foo1();
        var b = new Foo2();
        GenericMethod(a, b, out ReturnType result1); // work!
        ReturnType result2 = GenericMethod(a, b, out result2);
    }
}

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

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