我想編寫一個編譯器無法在運行時解析的通用擴展方法,雖然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