C#中接口成员的访问修饰符 [英] Access modifiers on interface members in C#

查看:26
本文介绍了C#中接口成员的访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到来自以下属性的编译错误.
错误是:

I am getting a compile error from the following property.
The error is:

修饰符‘public’对此项无效"

"The modifier 'public' is not valid for this item"

public System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
    get { return properties; }
    set { properties = value; }
}

但是如果我删除 IWorkItemControl 它编译正常.

but if I remove the IWorkItemControl it compiles fine.

为什么我会收到这个错误,签名中有/没有接口名称有什么区别?

Why am I getting this error and what is the difference of having / not having the interface name in the signature?

推荐答案

显式接口实现 不允许您指定任何访问修饰符.当您显式实现接口成员时(通过在成员名称之前指定接口名称),您可以仅使用该接口访问该成员.基本上,如果你这样做:

Explicit interface implementation does not let you specify any access modifiers. When you implement an interface member explicitly (by specifying the interface name before the member name), you can access that member only using that interface. Basically, if you do:

System.Collections.Specialized.StringDictionary IWorkItemControl.Properties
{
    get { return properties; }
    set { properties = value; }
}

你不能这样做:

MyClass x = new MyClass();
var test = x.Properties; // fails to compile
// You should do:
var test = ((IWorkItemControl)x).Properties; // accessible through the interface

EII 有几个用例.例如,您希望为您的类提供一个 Close 方法来释放获取的资源,但您仍然希望实现 IDisposable.你可以这样做:

There are several use cases for EII. For example, you want to provide a Close method for your class to free up acquired resources but you still want to implement IDisposable. You could do:

class Test : IDisposable {
    public void Close() {
        // Frees up resources
    }
    void IDisposable.Dispose() {
        Close();
    }
}

这样,类的消费者只能直接调用Close(他们甚至不会在Intellisense列表中看到Dispose)但你仍然可以使用Test 类在任何需要 IDisposable 的地方(例如在 using 语句中).

This way, the consumers of class can only call Close directly (and they won't even see Dispose in Intellisense list) but you can still use the Test class wherever an IDisposable is expected (e.g. in a using statement).

EII 的另一个用例是为两个接口提供同名接口成员的不同实现:

Another use case for EII is providing different implementations of an identically named interface member for two interfaces:

interface IOne {
   bool Property { get; }
}

interface ITwo {
   string Property { get; }
}

class Test : IOne, ITwo {
   bool IOne.Property { ... }
   string ITwo.Property { ... }
}

如您所见,如果没有 EII,甚至不可能在单个类中实现此示例的两个接口(因为属性仅在返回类型上有所不同).在其他情况下,您可能希望通过不同的接口为类的各个视图有意提供不同的行为.

As you see, without EII it's not even possible to implement both interfaces of this example in a single class (as the properties differ just in return type). In other cases, you might want to intentionally provide different behavior for individual views of a class through different interfaces.

这篇关于C#中接口成员的访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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