C# 语言设计:事件的显式接口实现 [英] C# Language Design: explicit interface implementation of an event

查看:29
本文介绍了C# 语言设计:事件的显式接口实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 C# 语言设计的小问题 :))

Small question about C# language design :))

如果我有这样的界面:

interface IFoo {
  int Value { get; set; }
}

可以使用 C# 3.0 自动实现的属性显式实现此类接口:

It's possible to explicitly implement such interface using C# 3.0 auto-implemented properties:

sealed class Foo : IFoo {
  int IFoo.Value { get; set; }
}

但是如果我在界面中有一个事件:

But if I had an event in the interface:

interface IFoo {
  event EventHandler Event;
}

并尝试使用类似字段的事件显式实现它:

And trying to explicitly implement it using field-like event:

sealed class Foo : IFoo {
  event EventHandler IFoo.Event;
}

我会得到以下编译器错误:

I will get the following compiler error:

错误 CS0071:事件的显式接口实现必须使用事件访问器语法

我认为类场事件是自动实现属性的某种二元论.

I think that field-like events is the some kind of dualism for auto-implemented properties.

所以我的问题是:进行这种限制的设计原因是什么?

推荐答案

我想这可能与您无法从类的其他成员调用显式接口实现这一事实有关:

I guess it might have to do with the fact that you can't call an explicit interface implementation from other members of the class:

public interface I
{
    void DoIt();
}

public class C : I
{
    public C()
    {
        DoIt(); // error CS0103: The name 'DoIt' does not exist in the current context
    }

    void I.DoIt() { }
}

请注意,您可以通过先向上转换到接口来调用该方法:((I)this).DoIt();.有点难看,但它有效.

Note that you can call the method by upcasting to the interface first:((I)this).DoIt();. A bit ugly but it works.

如果事件可以按照 ControlFlow(OP)的建议明确实现,那么您将如何实际引发它们?考虑:

If events could be explicitly implemented as ControlFlow (the OP) suggested, then how would you actually raise them? Consider:

public interface I
{
    event EventHandler SomethingHappened;
}

public class C : I
{
    public void OnSomethingHappened()
    {
        // Same problem as above
        SomethingHappened(this, EventArgs.Empty);
    }

    event EventHandler I.SomethingHappened;
}

在这里你甚至不能通过首先向上转换到接口来引发事件,因为事件只能从实现类中引发.因此,为显式实现的事件要求访问器语法似乎是完全合理的.

Here you cannot even raise the event by upcasting to the interface first, because events can only be raised from within the implementing class. It therefore seems to make perfect sense to require accessor syntax for explicitly implemented events.

这篇关于C# 语言设计:事件的显式接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆