在compimation中遇到一个奇怪的问题,说类没有实现接口.
让我们说av得到了一个类:
public Class MyClass
{
...
}
Run Code Online (Sandbox Code Playgroud)
和一个interace:
public Interface IMyInterface
{
MyClass PropertyOfMyClass {get;}
}
Run Code Online (Sandbox Code Playgroud)
现在是一个通用类:
public class MyGeneric<T> where T:MyClass
{
T PropertyOfMyClass
{
get{return ...;}
}
}
Run Code Online (Sandbox Code Playgroud)
直到这里,每个人都很好并且编译正确.
但是这会在编译时打破:
public class MyGeneric<T>:IMyInterace where T:MyClass
{
T PropertyOfMyClass
{
get{return ...;}
}
}
Run Code Online (Sandbox Code Playgroud)
说MyGeneric没有实现IMyInterface的方法.但显然确实如此,不是吗?
您无法从具有差异的接口实现属性(或方法).这不仅会影响泛型.例如:
public interface IFoo
{
object Bar();
}
public class Foo : IFoo
{
// This won't compile
string Bar() { return "hello"; }
}
Run Code Online (Sandbox Code Playgroud)
现在您可以通过显式接口实现来解决这个问题:
public class Foo : IFoo
{
// Make the interface implementation call the more strongly-typed method
object IFoo.Bar() { return Bar(); }
string Bar() { return "hello"; }
}
Run Code Online (Sandbox Code Playgroud)
这可能是你的答案 - 或者可能不是.我们需要确切地知道为什么要将属性声明为类型T而不仅仅是MyClass为了确定.
| 归档时间: |
|
| 查看次数: |
541 次 |
| 最近记录: |