2010-11-04 58 views
2

以下的意圖實現的接口的方法的約束類型參數是隻允許呼叫IRegistration<Foo>.As<IFoo>如果Foo實現IFoo到由另一種類型的

interface IRegistration<TImplementation> 
{ 
    void As<TContract>() where TImplementation : TContract; 
} 

這不是由C#3.0編譯器允許的。我得到以下錯誤:

'SomeNamespace.IRegistration.As()' does not define type parameter 'TImplementation'

有沒有辦法解決這個問題,除了把兩個類型參數放在方法聲明中?

這個問題受此啓發other question about Autofac

回答

3

您正試圖在類型參數列表中不存在的類型參數上添加約束。

這是你的意思嗎?

interface IRegistration<TImplementation> where TImplementation : TContract 
{ 
    void As<TContract>(); 
} 

雖然這也不會編譯 - 你不能在泛型上有一個通用的約束。

這將編譯,但可能不會產生你想要的方法本身的約束:

interface IRegistration<TImplementation,TContract> where TImplementation : TContract 
{ 
    void As<TContract>(); 
} 

看看這會做:

interface IRegistration<TImplementation,TContract> where TImplementation : TContract 
{ 
    void As(); 
} 

這樣一來,您使用TImplementation任何時間,它將被限制爲TContract,並且您仍然可以在As方法中使用TContract

你可以找到更多的信息here - 看看頁面結尾部分標題爲「類型參數爲約束」。

+0

嗯,不要認爲這有效 - 接口上的'TContract'與方法上的'TContract'不同。 – 2010-11-04 10:20:46

+0

@蒂姆羅賓遜 - 好點。我正在尋找將編譯和忘記需求的東西......答案已更新。 – Oded 2010-11-04 10:29:22

+0

同意你的更新答案 - 我想不出任何其他方式。 – 2010-11-04 10:38:32

相關問題