c# - 编译错误 : "The modifier ' public' is not valid for this item"while explicitly implementing the interface

标签 c# .net oop

我在类上创建 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/

相关文章:

c++ - 在 C++ 中如何从友元函数访问私有(private)函数?

C# 字段命名指南?

c# - 如何调用执行耗时任务的 DLL?

c# - 如何从 C# 将 const char* 传递给 C 函数?

.net - 将 Entity Framework 与历史数据一起使用

.net - 如何将 C# 应用程序分发到具有未知版本的 .Net 的计算机?

php - 依赖注入(inject),几乎每个类都依赖于其他几个类

c# - 从方法中检索调用方法名称

c# - 在 WPF 中使用 Unity Prism 在 TextBox 中键入时实时更新 TextBlock

c# - C# 中的动态相等