接口(interface)实现上的 c# 行为

标签 c# .net mono

我在 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 {}

就是这样。这让我可以直接替换 HtmlTextBoxHtmlDiv,它们使用它们现有的 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, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located

关于接口(interface)实现上的 c# 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20786071/

相关文章:

c# - BHO 在 Internet Explorer 的加载项列表中以 "unknown publisher"列出

c# - Quartz.NET - 这个单元测试不应该通过吗?

c# - 从 MySql 数据库收集数据以与变量进行比较

c# - 从更长的字符串中提取字符串

performance - MONO 的新遗物替代品?

c# - 是否可以在 Linux 上运行 Xamarin Mono?

c# - 用于设置不同修饰符来获取/设置的一行代码

c# - 定时器在待机模式下会发生什么?

c# - 在 C# 中,如何检查 TCP 端口是否可用?

f# - 用Mono运行F#代码