如何在C#中为扩展方法指定两个通用参数

时间:2011-02-21 21:22:26

标签: c# .net generics extension-methods

我正在尝试使用以下签名编写扩展方法

public static D GetModelFor<S, D>(this S source) 
            where S : BusinessBase

我有以下课程

public class Order : BusinessBase

我希望能够将Order类的实例上的扩展方法调用为

Order o = new Order();
SomeOtherClass s = o.GetModelFor<SomeOtherClass>();

但这不起作用。 C#编译器要求我指定S和D的类型。在这种情况下Order和SomeOtherClass。我在这里做错了吗?

========更多内部实施细节=========

    public static D GetModelFor<S, D>(this S source) 
        where D : IMappingProvider, new()
    {
        D d = new D();
        d.CreateMap();
        return Mapper.Map<S, D>(source);
    }

这里IMappingProvider是一个接口,它为类提供了一种为自动映射器注册地图的方法。如您所见,我需要在S

中使用Mapper.Map<>类型

2 个答案:

答案 0 :(得分:0)

是否有理由不仅仅做

public static T GetModelFor<T>(this BusinessBase source)

答案 1 :(得分:0)

  

我在这里做错了吗?

是 - 如果指定任何类型参数,则必须全部指定。

Order o = new Order();
SomeOtherClass s = o.GetModelFor<Order, SomeOtherClass>();
SomeOtherClass s2 = o.GetModelFor<BusinessBase, SomeOtherClass>();