泛型扩展方法中是否有额外的泛型参数? [英] Extra generic parameter in generic extension methods?

查看:65
本文介绍了泛型扩展方法中是否有额外的泛型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为通用类A提供一个扩展方法,该方法采用另一个通用类型(在本例中为TC),但我想这可能吗?

I would like make an extension method for the generic class A which takes yet another generictype (in this example TC), but i guess that aint possible?

class Program
{
    static void Main(string[] args)
    {
        var a = new A<B, B>();
        a.DoIt<B>();
    }
}

static class Ext
{
    public static A<TA, TB> DoIt<TA, TB, TC>(this A<TA, TB> a)
    {
        return a;
    }
}

class A<TA, TB> { }
class B { }

推荐答案

如果您可以接受语法上的微小更改,则有可能.

If you can accept a slight syntax change, then it would be possible.

将其更改为:

var a = new A<B, B>(); 
a.Do().It<B>(); 

诀窍在于,Do方法是 A< TA,TB> 上的扩展方法:

The trick is that the Do method is an extension method on A<TA, TB>:

public static Doer<TA, TB> Do<TA, TB>(this A<TA, TB> a)
{
    return new Doer<TA, TB>(a);
}

诀窍在于,该签名使类型推断可以从 a 中拾取TA和TB,因此您不必显式指定它们.

The trick is that this signature lets type inferincing pick up TA and TB from a so that you don't have to specify them explicitly.

Doer类提供您需要的通用方法:

The Doer class provides the generic method you need:

public class Doer<TA, TB>
{
    public void It<TC>() { }
}

这篇关于泛型扩展方法中是否有额外的泛型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆