【问题标题】:inheriting an interface and setting access-modifiers继承接口并设置访问修饰符
【发布时间】:2014-04-06 22:04:21
【问题描述】:

想做“私人集;”。有没有其他选择?

public interface IFoo
{
    IEnumerable data { get;  set; }

}

public class Foo : IFoo
{
    public IEnumerable data
    {
        get;
        private set;
    }

}

【问题讨论】:

  • 通过将其设为私有,您违反了接口的约定。

标签: inheritance interface access-modifiers


【解决方案1】:

您可以从界面中删除 set 访问器:

public interface IFoo
{
    IEnumerable data { get; }

}

或者你可以显式地实现接口,但是你需要以某种方式实现 set 方法:

public class Foo : IFoo
{

    public IEnumerable data
    {
        get;
        private set;
    }

    IEnumerable IFoo.data
    {
        get { return data; }
        set { throw new NotSupportedException(); }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-29
    • 2017-08-17
    • 2013-09-27
    • 2010-11-26
    • 2021-06-10
    • 2018-06-13
    • 2015-02-09
    • 2011-04-21
    相关资源
    最近更新 更多