【发布时间】: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());
}
}
【问题讨论】:
-
顺便说一句,我意识到我应该说“实现”接口而不是“继承”
-
我认为你是对的 Julien...哦,我可以在 'DuplicateMethod()' 中添加“void”,因为没有歧义......
标签: c# interface public explicit