我在 c# 中发现了一个行为,我想知道它是否在规范中(并且可以预期在所有平台和 .NET 运行时的新版本上工作)或者它是否是恰好发生的未定义行为工作,但可能随时停止编译。
那么,假设我想学习现有的类(class),例如:
public class HtmlTextBox
{
public string Text {get; set;}
}
public class HtmlDiv
{
public string Text {get; set;}
}
现在我真的希望他们实现一个通用的 IText 接口(interface),就像这样:
public interface IText
{
string Text {get; }
}
但我不能直接更改这些类,因为它们是外部库的一部分。现在有多种方法可以做到这一点,通过继承或使用装饰器。 但我惊讶地发现,只需执行此操作即可编译并在 .NET 4.5(Windows 7 64 位)上运行。
public class HtmlTextBox2 : HtmlTextBox, IText {}
public class HtmlDiv2 : HtmlDiv, IText {}
就是这样。这让我可以直接替换 HtmlTextBox
和 HtmlDiv
,它们使用它们现有的 Text
属性作为 IText
的实现。
我半预料编译器会对我大吼大叫,要求我提供 Text
的显式重新实现,但在 .NET 4.5 上这才有效:
IText h2 = new HtmlTextBox2{Text="Hello World"};
Console.WriteLine(h2.Text); //OUTPUT: hello world
事实上,我已经在单声道(无论 ideone.com 使用什么版本)和 mono does not yell at me either 上尝试过相同的方法
所以我想我可以开始了,但是在对严肃的代码进行尝试之前,我想检查一下我是否误解了这里真正发生的事情,或者我是否不能依赖它来工作。
最佳答案
是的,这是预期的行为。接口(interface)方法的实现不需要在实际应用接口(interface)的类中完成;它可以在任何祖先类中。
C# Language Specification 5.0在第 13.4.4 节中记录此内容;规则摘录:
The implementation of a particular interface member
I.M
, whereI
is the interface in which the memberM
is declared, is determined by examining each class or structS
, starting withC
and repeating for each successive base class ofC
, until a match is located
关于接口(interface)实现上的 c# 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20786071/