为什么显式接口成员实现,没有修饰符

时间:2016-05-20 11:51:28

标签: c# oop

为什么显式接口成员实现,没有修饰符

public interface ITest
{
    string Id { get; }
}

public class TestSeparately : ITest
{
    //Why an explicit interface member implementation, don't have modifier
    string ITest.Id
    {
        get { return "ITest"; }
    }
}

2 个答案:

答案 0 :(得分:0)

来自MSDN

  

在方法调用,属性访问或索引器访问中,无法通过其完全限定名称访问显式接口成员实现。显式接口成员实现只能通过接口实例访问,并且在这种情况下仅通过其成员名称引用。

因此,publicprotectedprivate等访问修饰符都没有任何意义。

请注意,这不会起作用:

TestSeparately ts = new TestSeparately();
string id = ts.Id; // compiler error, because Id is not a public property of TestSeparately

您需要将其置于ITest

string id = ((ITest)ts).Id; 

因此,访问修饰符对于显式接口实现没有用处。

答案 1 :(得分:0)

默认情况下,接口中的每个成员都是公共的,并且必须是这样的,因为接口定义了某个原型。但是,类或结构可以从多个接口继承,并且很可能这些接口具有相同的方法或属性。请考虑以下事项:

public interface ITest
{
    string Id { get; }
}

public interface ITest1
{
    string Id { get; }
}

public class TestSeparately : ITest, ITest1
{
//Why an explicit interface member implementation, don't have modifier
    string ITest.Id
    {
        get { return "ITest"; }
    }
    string ITest1.Id
    {
        get { return "ITest1"; }
    }
}

现在如果有一种方法可以隐式地将类转换为接口并以这种方式访问​​成员,从TestSeparately请求属性值Id,即返回TestSeparately的值.Id是什么?哪个接口编译器应该隐式转换并返回ID?是ITest.Id还是ITest1.I' d?看看问题所以是的,在显式实现中没有修饰符,并且总是需要使用显式转换来确定应该定位哪个接口,正如我所说,public是唯一的强制访问修饰符且不可更改。