简体   繁体   中英

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 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. 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. As you can see, I need type S to use in Mapper.Map<>

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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