我在类上创建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());
}
}
}
答案 0 :(得分:66)
使用界面的显式实现时,成员被迫在类本身中比私有更受限制。当强制访问修饰符时,您可能不会添加一个。
同样,在界面本身中,所有成员都是公开。如果您尝试在界面中添加修饰符,则会出现类似的错误。
为什么明确的成员(非常)是私人的?考虑:
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.
如果这些方法是公开的,那么您将遇到无法通过正常重载规则解析的名称冲突。
出于同样的原因,您甚至无法从M()
成员中呼叫class C
。您必须首先将this
强制转换为特定接口以避免相同的歧义。
class C : I1, I2
{
...
void X()
{
M(); // error, which one?
((I1)this).M(); // OK
}
}
答案 1 :(得分:11)
http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx: 当一个成员被显式实现时,它不能通过类实例访问,而只能通过接口的实例访问。
Customer customer = new Customer();
Console.WriteLine(customer.PrintName());
违反此
答案 2 :(得分:7)
显式实现接口时,不能使用访问修饰符。无论如何,成员将被绑定到接口,因此不需要指定访问修饰符,因为所有接口成员都是公共的,所有显式实现的成员也只能通过接口类型的成员访问(例如参见statichippo的答案)。 / p>
答案 3 :(得分:-1)
这是一个显式实现,接口成员的默认范围是public,而在类的情况下它是私有的,ergo,不需要使用Public修饰符,因为当我们调用该方法时它会只能通过接口的引用来调用。
根据“MSDN Explicit Interface Implementation”,实现显式接口的函数永远不会明确定义为public。它们默认是公开的。否则定义它们将毫无意义。
答案 4 :(得分:-3)
当我们想要使用上面示例的隐式实现时,以下是代码。
interface I1 { void M(); }
interface I2 { void M(); }
class C : I1, I2
{
public void M() { ... }
}
C c = new C();
c.M(); // Ok, no ambiguity. Because both Interfaces gets implemented with one method definition.