编译错误:显式实现接口时“修饰符‘public’对此项无效”

2023-12-26

我在创建时遇到此错误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. 

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

出于同样的原因,你甚至不能打电话M()从里面一个class C成员。你必须施放this首先到一个特定的接口以避免同样的歧义。

class C : I1, I2
{
   ...
   void X() 
   {  
     M();             // error, which one? 
     ((I1)this).M();  // OK 
   }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

编译错误:显式实现接口时“修饰符‘public’对此项无效” 的相关文章

随机推荐