我正在尝试编写一种通用的扩展方法,尽管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?)

这里是一些我可以想到的最简单形式的示例代码,它重现了该问题。我知道可以在GenericExtensionMethod中添加IOtherGenericInterface,但是我需要一个扩展方法,因为它需要在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/

10-11 04:09