c# - 为什么我们使用无成员接口(interface)?

标签 c# .net oop interface

编写没有成员的接口(interface)有什么意义?

INamingContainer是 .NET Framework 中的一个示例。它在 MSDN 中被描述为:

Identifies a container control that creates a new ID namespace within a Page object's control hierarchy. This is a marker interface only.

它是否只用于这种 block :

if (myControl is INamingContainer)
{
    // do something
}

或者它还有其他优点吗?

编辑:它被称为Marker Interface Pattern (感谢普雷特)

最佳答案

无成员接口(interface)用于在 C# 中提供类似混合的功能。所以给定一个 A 类:

class A : B { ... }

您可以通过定义接口(interface) IStuff 为其提供额外的功能(a-la 多重继承):

interface IStuff {}

然后在 A 中“实现”它:

class A : B, IStuff { ... }

然后添加额外的功能

class Methods {
  public static void Something(this IStuff stuff) {
    // some functionality here
  }
}

关于c# - 为什么我们使用无成员接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/653315/

相关文章:

c# - ASP.NET 图表和用户控制输出缓存

c# - 当使用 C# 图表 API 绘制的第一个点位于 (0,0) 时,X 轴值自动递增

C# WinForms 应用程序在到达 Program.Main() 末尾时不会关闭

c# - 是否有相当于 C#/.NET 的 Perl URI.pm 的版本?

javascript - 为什么在构建 Javascript 类层次结构时 Object.setPrototypeOf 不鼓励/效率低下?

c# - 日志记录类应该作为依赖项插入还是应该使用静态方法

c# - 如何检查枚举数组中是否存在枚举值?

c# - Process.Start 是否在父程序终止时终止子程序?

c++ - 哪种设计更好 : provide direct access to an owned object or give owning object forwarding methods to the owned object?

c# - DTO从客户端传输到服务端后变为null