继承接口的方法不能显式声明为 "Public"



也许有人能给我一个快速的答案…

在"class DuplicateInterface class:MyInterface1,MyInterface2"下的以下完全无用的代码中。

为什么我不能显式地写"public string MyInterface2.p()"
但是"public string P()"one_answers"string MyInterface2.P())"是有效的。

我知道默认情况下,所有接口方法(属性等)都是隐式的"public",但我试图在继承类中显式,结果导致"错误CS0106:修饰符"public"对此项无效"。

using System;
interface MyInterface1
{
    void DuplicateMethod();
    // interface property
    string P
    {   get;    }
}
interface MyInterface2
{
    void DuplicateMethod();
    // function ambiguous with MyInterface1's property
    string P();
}
// must implement all inherited interface methods
class DuplicateInterfaceClass : MyInterface1, MyInterface2
{
    public void DuplicateMethod()
    {
        Console.WriteLine("DuplicateInterfaceClass.DuplicateMethod");
    }
    // MyInterface1 property
    string MyInterface1.P
    {   get
        {   return ("DuplicateInterfaceClass.P property");  }
    }
    // MyInterface2 method
    // why? public string P()...and not public string MyInterface2.P()?
    string MyInterface2.P()
    {   return ("DuplicateInterfaceClass.P()"); }
}
class InterfaceTest
{
    static void Main()
    {
        DuplicateInterfaceClass test = new DuplicateInterfaceClass();       
        test.DuplicateMethod();     
        MyInterface1 i1 = (MyInterface1)test;
        Console.WriteLine(i1.P);
        MyInterface2 i2 = (MyInterface2)test;
        Console.WriteLine(i2.P());
    }
}

我收到了来自Resharper的以下明确消息:"修饰符'public'对于显式接口实现无效。"

但你可以做到:

class DuplicateInterfaceClass : MyInterface1, MyInterface2
{
 public void DuplicateMethod()
 {
  Console.WriteLine("DuplicateInterfaceClass.DuplicateMethod");
 }
 string MyInterface1.P
 { get { return "DuplicateInterfaceClass.P"; } }
 string MyInterface2.P()
 { return "DuplicateInterfaceClass.P()"; }
 public string P()
 { return ((MyInterface2)this).P(); }
}

最新更新