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

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

问题描述

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

Small question about C# language design :))

如果我有一个像这样的接口:

If I had an interface like this:

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)本).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天全站免登陆