我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();
}
}
Run Code Online (Sandbox Code Playgroud)
控制台测试应用代码:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
Hen*_*man 73
当使用接口的显式实现时,成员被迫在类本身中比私有更受限制.当强制访问修饰符时,您可能不会添加一个.
同样,在界面本身中,所有成员都是公开的.如果您尝试在界面中添加修饰符,则会出现类似的错误.
为什么明确的成员(非常)是私人的?考虑:
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.
Run Code Online (Sandbox Code Playgroud)
如果这些方法是公共的,那么您将有一个名称冲突,无法通过正常的重载规则来解决.
出于同样的原因,你甚至无法M()从class C会员内部打电话.您必须首先this转换为特定接口以避免相同的歧义.
class C : I1, I2
{
...
void X()
{
M(); // error, which one?
((I1)this).M(); // OK
}
}
Run Code Online (Sandbox Code Playgroud)
hac*_*sid 11
http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx:当一个成员被显式实现时,它不能通过类实例访问,而只能通过接口的实例访问.
Customer customer = new Customer();
Run Code Online (Sandbox Code Playgroud)
Console.WriteLine(customer.PrintName());
违反此规定
显式实现接口时,不能使用访问修饰符.无论如何,成员将被绑定到接口,因此不需要指定访问修饰符,因为所有接口成员都是公共的,所有显式实现的成员也只能通过接口类型的成员访问(例如参见statichippo的答案).
| 归档时间: |
|
| 查看次数: |
57455 次 |
| 最近记录: |