我正在尝试找出一种方法来强制我所有的接口(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/