我在一个类上创建一个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());

        }
    }
}

推荐答案

当使用接口的explicit实现时,成员被迫使用比类本身中的private更严格的限制.当访问修饰符被强制时,您不能添加一个.

同样,在界面本身中,所有成员都是public.如果您试图在接口内添加修饰符,您将得到类似的错误.

为什么显性成员(非常)是私有的?请考虑:

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. 

如果这些方法是公共的,则会出现无法通过常规重载规则解决的名称冲突.

出于同样的原因,你甚至不能从class C成员内部拨打M().为了避免同样的歧义,您必须首先将this转换为特定的接口.

class C : I1, I2
{
   ...
   void X() 
   {  
     M();             // error, which one? 
     ((I1)this).M();  // OK 
   }
}

.net相关问答推荐

在PowerShell中,XML子对象和属性是对象属性.它怎麽工作?

从容器化客户端应用程序连接到 OPC-UA 服务器

使用 MassTransit、.NET Core 和 RabbitMQ 的设计挑战

CurrentCulture、InvariantCulture、CurrentUICulture 和 InstalledUICulture 之间的区别

将毫秒转换为人类可读的时间间隔

.NET 的 Visual Studio 调试器提示和技巧

.NET 中是否有一种简单的方法来获得数字的st、nd、rd和th结尾?

log4net 与 TraceSource

泛型方法是如何、何时、何地具体化的?

Linq查询分组并 Select 第一个项目

将双精度转换为带有 N 个小数的字符串,点作为小数分隔符,并且没有千位分隔符

将 C# 编译为本机?

我不了解应用程序域

在 C#/.NET 中组合路径和文件名的最佳方法是什么?

将字典值转换为数组

了解 C# 中的协变和逆变接口

读取 XML(从字符串)并获取一些字段 - 读取 XML 时出现问题

为什么 .NET 中没有 Tree 类?

是否可以判断对象是否已附加到实体框架中的数据上下文?

ValueTypes 如何从 Object (ReferenceType) 派生并且仍然是 ValueTypes?