可能会有人给我一个快速的答案......
在以下完全无用的代码中,在'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());
}
}
答案 0 :(得分: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(); }
}