簡體   English   中英

如何在C#中為擴展方法指定兩個通用參數

[英]How to specify two generic parameters for an extension method in C#

我正在嘗試使用以下簽名編寫擴展方法

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是一個接口,該接口為類提供了一種為自動映射器注冊地圖的方法。 如您所見,我需要在Mapper.Map<>使用S類型。

是否有理由不只是做

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

我在這里做錯什么嗎?

是-如果指定任何類型參數,則必須全部指定。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM