扩展方法冲突

时间:2016-07-12 13:32:34

标签: c# extension-methods

我有一个接口的扩展方法,一个在实现接口的类的实例上执行操作,另一个在实现接口的类的集合上执行操作。问题是编译器总是使用第一个扩展方法,这会产生编译错误,所以我不能使用集合版本。

public interface ISomeInterface
{
}

public class SomeClass : ISomeInterface
{
}

public static class SomeClassExtensions
{
    public static T DoSomething<T>(this T item) where T : class, ISomeInterface
    {
        return item;
    }

    public static IEnumerable<T> DoSomething<T>(this IEnumerable<T> items) where T : class, ISomeInterface
    {
        return items;
    }
}

internal class Program
{
    private static void Main()
    {
        var items = new[]
        {
            new SomeClass()
        };

        items.DoSomething(); // compiler error
    }
}

错误很明显,编译器正在尝试使用第一种扩展方法:

  

类型'ConsoleApplication1.SomeClass []'不能在泛型类型或方法'SomeClassExtensions.DoSomething(T)'中用作类型参数'T'。从'ConsoleApplication1.SomeClass []'到'ConsoleApplication1.ISomeInterface'没有隐式引用转换。

显然,我可以重命名两种扩展方法中的一种,但这是最后的手段,因为这是一个开源项目,我试图避免偏离既定的命名约定。

我没有关于如何强制我需要工作的想法,也许有办法添加或调整泛型类型约束?

1 个答案:

答案 0 :(得分:2)

这应该这样做

var items = new[]
{
    new SomeClass()
};

items.DoSomething<SomeClass>();

当然,假设itemsSomeClass[]