开发者

Why can't an internal event in a class implement an event on an internal interface?

开发者 https://www.devze.com 2023-03-17 23:04 出处:网络
I have an internal interface which defines some events and a sample class which implements the interface:

I have an internal interface which defines some events and a sample class which implements the interface:

internal interface IMyEvents
{
    event EventHandler MyEvent;
}

p开发者_如何学Goublic class MyClass : IMyEvents
{
    internal event EventHandler MyEvent;

    public void DoSomething()
    {
        if (MyEvent != null) MyEvent(this, new EventArgs());
    }
}

When I try to compile, I get the following error:

error CS0737: 'MyClass' does not implement interface member '.IMyEvents.MyEvent'. 'MyClass.MyEvent' cannot implement an interface member because it is not public.

What's going on here? It's an internal interface, so I don't see why the event has to be public.


Members that implement an interface are required to be either public or explicit in C#, regardless of the accessibility of the interface.

This is a "simplifying" rule; if you do otherwise then you get into the quagmire that is C++ accessibility, where there is public inheritance, private inheritance, and so on. We'd rather keep it simple: if you want to implement an interface, either make a public member, or say explicitly that you are implementing the interface.


You need to explicitly implement IMyEvents.

public class MyClass : IMyEvents
{
    // ...

    event EventHandler IMyEvents.MyEvent
    {
        add { MyEvent += value; }
        remove { MyEvent -= value; }
    }
}


C# doesn't allow that because it insists that either the implementing member is public or that it's an explicit implementation (in which case it will end up being private, but you can still access it through a reference to the interface). You can do that in VB.NET though.

0

精彩评论

暂无评论...
验证码 换一张
取 消