简体   繁体   English

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

[英]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.

相关问题 如何在c#中指定通用列表类型扩展方法的参数 - How to specify parameter for generic list type extension method in c# C#:如何接受两个通用参数 - C# : how to accept two generic parameters C#中的通用扩展方法 - Generic extension method in C# c# 如何在工厂方法中返回指定通用 class 的 class - c# How to return a class that specify a generic class in factory method 如何部分指定泛型方法类型参数 - How to specify generic method type parameters partly 如何在C#抽象方法中指定可选的匿名可枚举参数 - how to specify optional anonymous ienumerable parameters in c# abstract method 在C#中,我如何创建一个扩展方法,该方法采用带有泛型参数的Lambda函数,Func <T, TResult> 作为参数。 - In C# how do I create an extension method that takes a lambda with generic parameters, Func<T, TResult> as a parameter. 如何编写通用扩展方法转换C#中的类型 - How to Write Generic Extension Method to Convert Type in C# 如何在C#中为动态创建的类型调用通用扩展方法 - How to call generic extension method for dynamically created type in c# 如何在C#中将此功能编写为通用扩展方法? - How to write this functionality as a generic extension method in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM