[英]How to specify two generic parameters for an extension method in C#
I'm trying to write an extension method with following signature 我正在尝试使用以下签名编写扩展方法
public static D GetModelFor<S, D>(this S source)
where S : BusinessBase
I have following class 我有以下课程
public class Order : BusinessBase
I want to be able to call the extension method on an instance of Order class as 我希望能够在Order类的实例上调用扩展方法为
Order o = new Order();
SomeOtherClass s = o.GetModelFor<SomeOtherClass>();
But this does not work. 但这是行不通的。 The C# compiler is asking me to specify both the types of S and D. In this case Order and SomeOtherClass.
C#编译器要求我同时指定S和D的类型。在这种情况下,请输入Order和SomeOtherClass。 Am I doing anything wrong here?
我在这里做错什么吗?
======== More Details of the internal implementation ========= ========更多内部实现细节=========
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);
}
Here IMappingProvider
is an interface which gives a class a way to register the maps for auto-mapper. 这里的
IMappingProvider
是一个接口,该接口为类提供了一种为自动映射器注册地图的方法。 As you can see, I need type S
to use in Mapper.Map<>
如您所见,我需要在
Mapper.Map<>
使用S
类型。
Is there a reason for not just doing 是否有理由不只是做
public static T GetModelFor<T>(this BusinessBase source)
? ?
Am I doing anything wrong here?
我在这里做错什么吗?
Yes - if you specify any type parameters, you must specify them all. 是-如果指定任何类型参数,则必须全部指定。
Order o = new Order();
SomeOtherClass s = o.GetModelFor<Order, SomeOtherClass>();
SomeOtherClass s2 = o.GetModelFor<BusinessBase, SomeOtherClass>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.