2010-04-22 123 views
6

在compimation中遇到一個奇怪的問題,說一個類沒有實現一個接口。通用類實現接口失敗

比方說一個V有一個類:

public Class MyClass 
{ 
... 
} 

而一個interace:

public Interface IMyInterface 
{ 
MyClass PropertyOfMyClass {get;} 
} 

現在泛型類:

public class MyGeneric<T> where T:MyClass 
{ 
    T PropertyOfMyClass 
    { 
    get{return ...;} 
    } 
} 

直到這裏逝去的罰款和編譯權。

但是,這將打破在編譯的時候:

public class MyGeneric<T>:IMyInterace where T:MyClass 
    { 
     T PropertyOfMyClass 
     { 
     get{return ...;} 
     } 
    } 

話說MyGeneric不IMyInterface的都實現方法。但顯然它確實,不是?

+0

認爲我不明白的是,如果T是MyClass的類型或後代,那麼屬性T PropertyOfMyClass等於MyClass PropertyOfMyClass。那麼爲什麼不能編譯? – Pitming 2010-04-22 11:54:31

回答

6

您不能從具有差異的接口實現屬性(或方法)。這不僅影響泛型。例如:

public interface IFoo 
{ 
    object Bar(); 
} 

public class Foo : IFoo 
{ 
    // This won't compile 
    string Bar() { return "hello"; } 
} 

現在你可以得到這一輪以顯式接口實現:

public class Foo : IFoo 
{ 
    // Make the interface implementation call the more strongly-typed method 
    object IFoo.Bar() { return Bar(); } 

    string Bar() { return "hello"; } 
} 

這可能是你的答案 - 也可能不會。我們需要準確地知道您爲什麼要聲明該房產爲T而非僅僅MyClass

+0

我不想返回一個MyClass實例,因爲我的類下有完整的層次結構,並且泛型沒有投射就返回了正確的類。 – Pitming 2010-04-22 11:55:50

1

另一個解決辦法是使接口通用本身:

public interface IMyInterface<T> where T : MyClass 
{ 
    T PropertyOfMyClass { get; } 
} 

然後,您可以使用它在一個類:

public class MyGenericClass<T> : IMyInterface<T> where T : MyClass 
{ 
    T PropertyOfMyClass 
    { 
     get { ... } 
    } 
} 

注意,使用此實現,在T上的約束通用類可以不同於接口上的類,只要它確保接口約束得到遵守:

public class MyOtherClass : MyClass 
{ 
} 

public class MyOtherGenericClass<T> : IMyInterface<T> where T : MyOtherClass 
{ 
    T PropertyOfMyClass 
    { 
     get { ... } 
    } 
} 
+0

當然,但我的界面可能不會成爲通用的... – Pitming 2010-04-22 11:56:25