【问题标题】:How to specify two generic parameters for an extension method in C#如何在 C# 中为扩展方法指定两个泛型参数
【发布时间】:2011-02-21 21:22:26
【问题描述】:

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

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&lt;&gt; 中使用

【问题讨论】:

    标签: c# .net generics extension-methods


    【解决方案1】:

    有没有理由不只是做

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

    ?

    【讨论】:

    • 是的。我希望 GetModelFor 方法返回 T 以外类型的对象。
    • @Suhas:那么,您能展示一些您计划的实施吗?我认为您的 GetModelFor&lt;SomeOtherClass&gt; 示例中的参数应该是 D,这与我的行在这里匹配。
    • 你是对的,那就是D。但我还需要指定S,以便GetModelFor&lt;SomeOtherClass&gt; 成为S 类型的扩展方法
    • @Suhas:我仍然不明白为什么你不能像我建议的那样做。发布一个带有两个类型参数的示例以及您在方法中实际拥有的内容怎么样?
    • 我现在明白你的意思了。我在上面的原始问题中添加了GetModelFor 的实现细节。我需要为自动映射器指定类型S
    【解决方案2】:

    我在这里做错了吗?

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

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

    【讨论】:

    • 我正在尝试实现一个扩展方法,以便摆脱指定第一个参数的需要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2010-09-09
    • 1970-01-01
    相关资源
    最近更新 更多