gpt4 book ai didi

c# - 从其他接口(interface)继承的接口(interface)的显式 C# 接口(interface)实现

转载 作者:太空狗 更新时间:2023-10-30 00:22:02 26 4
gpt4 key购买 nike

考虑以下三个接口(interface):

interface IBaseInterface
{
event EventHandler SomeEvent;
}

interface IInterface1 : IBaseInterface
{
...
}

interface IInterface2 : IBaseInterface
{
...
}

现在考虑以下同时实现 IInterface1 和 IInterface 2 的类:

class Foo : IInterface1, IInterface2
{
event EventHandler IInterface1.SomeEvent
{
add { ... }
remove { ... }
}

event EventHandler IInterface2.SomeEvent
{
add { ... }
remove { ... }
}
}

这会导致错误,因为 SomeEvent 不是 IInterface1 或 IInterface2 的一部分,而是 IBaseInterface 的一部分。

Foo 类如何同时实现 IInterface1 和 IInterface2?

最佳答案

你可以使用泛型:

interface IBaseInterface<T> where T : IBaseInterface<T>
{
event EventHandler SomeEvent;
}

interface IInterface1 : IBaseInterface<IInterface1>
{
...
}

interface IInterface2 : IBaseInterface<IInterface2>
{
...
}

class Foo : IInterface1, IInterface2
{
event EventHandler IBaseInterface<IInterface1>.SomeEvent
{
add { ... }
remove { ... }
}

event EventHandler IBaseInterface<IInterface2>.SomeEvent
{
add { ... }
remove { ... }
}
}

关于c# - 从其他接口(interface)继承的接口(interface)的显式 C# 接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2796188/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com