【问题标题】:Inherited Interface's Method Can't Be Explicitly Declare as "Public"继承接口的方法不能显式声明为“Public”
【发布时间】:2012-03-20 17:53:30
【问题描述】:

可能有人可以快速回答我...

在以下完全无用的代码中,在“class DuplicateInterfaceClass : MyInterface1, MyInterface2”下。

为什么我不能显式写“public string MyInterface2.P()”?
但是“public string P()”和“string MyInterface2.P()”可以工作。

我了解默认情况下所有接口方法(属性等)都是隐式“公共”的,但我尝试在继承类中显式导致“错误 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());
    }
}

【问题讨论】:

标签: c# interface public explicit


【解决方案1】:

我收到了来自 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(); }
}

【讨论】:

  • 感谢 Julien 确实给了我在 Main()... Console.WriteLine(((IMyInterface2)test).P()) 中使用以下内容的想法;
猜你喜欢
  • 2019-07-16
  • 2011-01-17
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 2010-09-06
  • 2016-02-16
  • 2017-10-23
相关资源
最近更新 更多