我想编写一个编译器无法在运行时解析的通用扩展方法,虽然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?)
这里是最简单的形式,一些示例代码,我可以拿出能重现问题。我知道我可以在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
}
}
实际的编译器错误怎么样? “这不能编译”没有帮助... – 2013-04-22 12:07:53
找到扩展方法问题的一个好方法是使用非扩展方法语法来调用它们。当你尝试时会发生什么? – dtb 2013-04-22 12:11:58
好点@DanielHilgarth,我刚刚添加了实际的错误。 – 2013-04-22 12:13:16