44

我有一個泛型類,我試圖實現隱式類型轉換。雖然它主要工作,但它不適用於接口鑄造。經過進一步調查,我發現有一個編譯器錯誤:「接口的用戶定義轉換」適用。雖然我知道這應該在某些情況下實施,但我試圖做的確看起來像是合法的情況。隱式運算符使用接口

下面是一個例子:使用它

public class Foo<T> where T : IBar 
{ 
    private readonly T instance; 

    public Foo(T instance) 
    { 
     this.instance = instance; 
    } 
    public T Instance 
    { 
     get { return instance; } 
    } 
    public static implicit operator Foo<T>(T instance) 
    { 
     return new Foo<T>(instance); 
    } 
} 

代碼:

var concreteReferenceToBar = new ConcreteBar(); 
IBar intefaceReferenceToBar = concreteReferenceToBar; 
Foo<ConcreteBar> concreteFooFromConcreteBar = concreteReferenceToBar; 
Foo<IBar> fooFromConcreteBar = concreteReferenceToBar; 
Foo<IBar> fooFromInterfaceBar = intefaceReferenceToBar; // doesn't work 

有誰知道解決辦法,或任何人都可以以令人滿意的方式解釋了爲什麼我shuouldn't能夠投interfaceReferenceToBar隱含到Foo<IBar>,因爲在我的情況下它沒有被轉換,但只包含在Foo內?

編輯: 它看起來像協變可能會提供救贖。我們希望C#4.0規範允許使用協方差隱式轉換接口類型。

回答

46

你不能這樣做的原因是因爲它是在C#語言規範明令禁止:

A class or struct is permitted to declare a conversion from a source type S to a target type T provided all of the following are true:

  • ...
  • Neither S nor T is object or an interface-type.

User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.

Source

+0

據我所知,這是部分規範,在某些情況下,一個接口的隱式轉換應該是無效的,但總的來說呢? – 2008-09-27 12:59:09