【问题标题】:Why cant I expose an implemented interface method?为什么我不能公开一个已实现的接口方法?
【发布时间】:2012-04-15 23:33:52
【问题描述】:

我一直在尝试一些 n 层架构,我真的很想知道为什么这段代码无法编译...

它说修饰符 public 对这个项目无效。但为什么不呢?我需要能够从 BLL 对象访问 IRepository.AddString() 项,但它不会让我将其公开....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BLL myBLL = new BLL();

        }
    }

    interface IRepository<T>
    {
        void AddString();
    }

    interface IStringRepo : IRepository<string>
    {
        List<string> GetStrings();
    }

    public class BLL : IStringRepo
    {
        public List<string> FilterStrings()
        {
            return new List<string>() { "Hello", "World" };
        }

        public List<string> IStringRepo.GetStrings()
        {
            throw new NotImplementedException();
        }

        public void IRepository<string>.AddString()
        {
            throw new NotImplementedException();
        }
    }
}

【问题讨论】:

    标签: c# interface


    【解决方案1】:

    这是一个explicitly-implemented member,它始终是私有的。

    从声明中删除 IStringRepo. 以创建一个也实现该接口的普通公共成员。

    【讨论】:

      【解决方案2】:

      显式实现的接口不能使用可见性修饰符。

      public List<string> IStringRepo.GetStrings() 
      

      应该是:

      public List<string> GetStrings() 
      

      【讨论】:

        猜你喜欢
        • 2010-11-18
        • 1970-01-01
        • 2011-04-24
        • 2011-04-26
        • 2021-11-01
        • 2017-09-13
        • 2015-02-12
        • 2023-03-13
        • 1970-01-01
        相关资源
        最近更新 更多