我在类上创建 public
方法以显式实现 interface
时遇到此错误。我有一个解决方法:通过删除 PrintName
方法的显式实现。但我很惊讶为什么会收到此错误。
任何人都可以解释错误吗?
库代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test.Lib1
{
public class Customer : i1
{
public string i1.PrintName() //Error Here...
{
return this.GetType().Name + " called from interface i1";
}
}
public interface i1
{
string PrintName();
}
interface i2
{
string PrintName();
}
}
控制台测试应用代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Test.Lib1;
namespace ca1.Test
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
Console.WriteLine(customer.PrintName());
//i1 i1o = new Customer();
//Console.WriteLine(i1o.printname());
//i2 i2o = new Customer();
//Console.WriteLine(i2o.printname());
}
}
}
最佳答案
当使用接口(interface)的显式实现时,成员被迫使用比类本身的private更受限制的东西。当强制访问修饰符时,您可能不会添加一个。
同样,在界面本身中,所有成员都是public。如果您尝试在界面内添加修饰符,您将收到类似的错误。
为什么显式成员(非常)私有(private)?考虑:
interface I1 { void M(); }
interface I2 { void M(); }
class C : I1, I2
{
void I1.M() { ... }
void I2.M() { ... }
}
C c = new C();
c.M(); // Error, otherwise: which one?
(c as I1).M(); // Ok, no ambiguity.
如果这些方法是公共(public)的,您将遇到无法通过正常重载规则解决的名称冲突。
出于同样的原因,您甚至不能从 C 类
成员内部调用 M()
。您必须先将 this
转换为特定接口(interface),以避免出现同样的歧义。
class C : I1, I2
{
...
void X()
{
M(); // error, which one?
((I1)this).M(); // OK
}
}
关于c# - 编译错误 : "The modifier ' public' is not valid for this item"while explicitly implementing the interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669031/