c# - 通用扩展方法的编译器错误

标签 c# generics extension-methods

我正在尝试编写编译器无法在运行时解析的通用扩展方法,尽管 visual studio 的 intellisense 确实找到了它。

编译器错误是'SampleSolution.OtherGenericClass<SampleSolution.IGenericInterface<SampleSolution.ISimpleInterface>,SampleSolution.ISimpleInterface>' does not contain a definition for 'GenericExtensionMethod' and no extension method 'GenericExtensionMethod' accepting a first argument of type 'SampleSolution.OtherGenericClass<SampleSolution.IGenericInterface<SampleSolution.ISimpleInterface>,SampleSolution.ISimpleInterface>' could be found (are you missing a using directive or an assembly reference?)

这是我能想到的最简单形式的一些示例代码,它可以重现该问题。我知道我可以添加 GenericExtensionMethodIOtherGenericInterface , 但我需要一个扩展方法,因为它需要在 IOtherGenericInterface 之外实现。

public interface ISimpleInterface
{

}

public interface IGenericInterface<T>
{

}

public class GenericClass<T> : IGenericInterface<T>
{

}

public interface IOtherGenericInterface<TGenericDerived>
{

}

public class OtherGenericClass<TGenericInterface, TSimpleInterface> : 
    IOtherGenericInterface<TGenericInterface>
    where TGenericInterface : IGenericInterface<TSimpleInterface>
{

}

public static class GenericExtensionMethods
{
    public static IOtherGenericInterface<TGenericInterface> 
        GenericExtensionMethod<TGenericInterface, TSimple>(
            this IOtherGenericInterface<TGenericInterface> expect)
        where TGenericInterface : IGenericInterface<TSimple>
    {
        return expect;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var exp = new OtherGenericClass<IGenericInterface<ISimpleInterface>,
                                        ISimpleInterface>();

        //exp.GenericExtensionMethod(); // This doesn't compile
    }
}

最佳答案

它没有足够的信息来明确解析泛型类型参数;你将不得不使用:

exp.GenericExtensionMethod<IGenericInterface<ISimpleInterface>, ISimpleInterface>();

特别注意,where 约束在解析之后 得到验证 - 它们本身不参与解析 - 因此在解析期间,它只能推断出 TGenericInterface.

关于c# - 通用扩展方法的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16146740/

相关文章:

c# - CRM 2011 - 从加入的实体中检索 FormattedValues

c# - 动态压缩 n 列表

c# - C# 中的 String.Format 和 Composite String 有什么区别?

C# 数据库示例项目

java - 强制两个参数化类型不同java

C# - 使用通用枚举(或控制列表的替代方法)

c# - 检查 T 泛型类型是否具有 C# 中的属性 S(泛型)

c# - NHibernate QueryOver 的按位运算和扩展方法

asp.net-mvc-4 - 我应该将扩展方法放在 ASP.Net MVC 中的哪个文件夹中?

c# - 最佳实践 : C# Extension methods namespace and promoting extension methods