【问题标题】:Explicit Interface Implementation demanded, but only one interface in use?需要显式接口实现,但只使用一个接口?
【发布时间】:2014-12-13 19:47:57
【问题描述】:

为什么以下代码必须使用显式接口实现语法定义“CalcUsable”? (见最后一行代码)如果我使用非显式语法(即公共十进制 CalcUsable)我会收到“不一致的可访问性”错误,具体来说:

“参数类型 ...List (IVoucher) 比方法 CalcUsable(...) 更难访问”

interface IVoucher
{
    string Serial { get; }
    decimal FaceValue { get; }
    string DiscountType { get; }
    string ApplyMsg { get; }
    string RejectMsg { get; }
    decimal CalcUsable(List<Product> products, List<IVoucher> vouchers);
}

// 'GiftVoucher' models the simple voucher which has no use restrictions.
//
public class GiftVoucher : IVoucher
{
    public string Serial { get; private set; }
    public decimal FaceValue { get; private set; }
    public string DiscountType { get; private set; }
    public string ApplyMsg { get; private set; }
    public string RejectMsg { get; private set; }

    public GiftVoucher(string serial, decimal faceValue)
    {
        Serial = serial;
        FaceValue = faceValue;
        ApplyMsg = string.Empty;
        RejectMsg = string.Empty;
        DiscountType = "Gift";
    }

    // 'CalcUsable' provides the voucher applicability logic.  
    //
    decimal IVoucher.CalcUsable(List<Product> products, List<IVoucher> vouchers)
    {
         blar, blar, blar...

【问题讨论】:

  • 尝试公开你的界面
  • 谢谢,这行得通!但是为什么???

标签: c# interface explicit-interface


【解决方案1】:

GiftVoucher 类是公共的,而IVoucher 接口不是。因此,无法从 IVoucher 不可用的任何地方调用 CalcUsable,因为该方法采用了不可访问类型的 List

正如 JRLambert 建议的那样,公开接口应该可以解决这个问题。

【讨论】:

  • 我以为界面的默认可访问性是公开的?如果不是,那是什么?
  • C# 中类型的默认访问修饰符是internal(我不确定嵌套类型)。
  • 最好从类中删除public修饰符(以便使其internal就像界面一样)。
  • @CodeCabbie 接口的成员(例如方法)的默认可访问性是public。它是唯一允许的访问级别,因此您甚至不能指定它。示例:您在接口内的声明decimal CalcUsable(List&lt;Product&gt; products, List&lt;IVoucher&gt; vouchers);publicinterface 本身的默认访问级别取决于接口的直接成员。如果它是namespace 的直接成员,则应用命名空间的默认可访问性,即internal。但如果接口是类或结构的成员,private
猜你喜欢
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 2010-09-29
相关资源
最近更新 更多