c# - 如何强制多个接口(interface)包含相同的属性?

标签 c# inheritance properties interface

我正在尝试找出一种方法来强制我所有的接口(interface)都包含相同名称/类型的属性。

例如:我有两个接口(interface); IGetAlarms 和 IGetDiagnostics。每个接口(interface)都将包含特定于接口(interface)本身的属性,但是我想强制这两个接口(interface)(以及以后可能添加的所有其他接口(interface))包含同名的属性。所以,结果可能看起来像这样:

interface IGetAlarms
{
    string GetAlarms();
    DateTime LastRuntime { get; set; }
}

interface IGetDiagnostics
{
    string GetDiagnostics();
    DateTime LastRuntime { get; set; } 
}

请注意,这两个接口(interface)都包含一个名为 LastRuntime 的 DateTime 属性。

我想知道是否有某种方法可以强制稍后添加的其他接口(interface)包含 DateTime LastRuntime 属性。我天真地试图让我的所有接口(interface)实现另一个接口(interface) (IService) - 其中包括 LastRuntime 属性。但是,这并不能解决我的问题,因为这只是强制类实现属性 - 而不是所有接口(interface)。

谢谢。

最佳答案

一个接口(interface)可以继承自其他接口(interface)。

interface IDerived : IBase
{
    string Foo { get; set; }
}

interface IBase
{
    DateTime LastRunDate { get; set; }
}

任何派生自 IDerived 的类都必须实现 IBase 的方法/属性。

class Derived : IDerived 
{
    #region IDerived Members

    public string Foo { get; set; }

    #endregion

    #region IBase Members

    public DateTime LastRunDate {get;set;}

    #endregion
}

关于c# - 如何强制多个接口(interface)包含相同的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2512921/

相关文章:

c# - 方法覆盖和可选参数

c# - 没有无参数构造函数的对象作为类的属性

ios - objective-c :通过自定义根类允许类别中的属性

c# - 只有 XAML 的数据网格的 WPF 焦点行

c# - 如何将多个 View 的DataContext设置为ViewModel的一个实例

c# - Kendo MVC Core - 网格 - 无法通过路线获取数据 - 400 错误请求

c++ - 广义复制构造函数

c++ - 冲突声明(外部基础与派生)

python - 关于 python 类 __init__ 和装饰器

c# - 带有列表框的 foreach 的奇怪问题