泛型扩展方法的编译器错误

本文关键字:编译器 错误 方法 扩展 泛型 | 更新日期: 2023-09-27 18:10:15

我正试图编写一个编译器在运行时无法解析的通用扩展方法,尽管visual studio的智能感知确实找到了它。

编译错误是'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?)

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