将setter添加到派生接口 [英] Adding a setter to a derived interface

查看:67
本文介绍了将setter添加到派生接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以某种方式在C#中实现此行为:

Is it possible somehow to achieve this behavior in C#:

public interface IReadOnly
{
    Data Value { get; }
}

internal interface IWritable : IReadOnly 
{
    Data Value { get; set; }
}

我希望能够将readonly接口公开给外部程序集,但是在内部使用可写接口(我也可以用不同的方式实现)。

I want to be able to expose a readonly interface to outside assemblies, but use a writable interface internally (which I could also implement in different ways).

我知道我可以使用抽象类来实现 IReadOnly 但添加了setter,但这迫使我从该类派生所有内部实现。

I know I can use an abstract class which implements IReadOnly but adds setters, but that forces me to derive all internal implementations from that class.

推荐答案

这不是问题:

public interface IReadOnly {
    Data Value { get; }
}

internal interface IWritable : IReadOnly {
    new Data Value { get; set; }
}

internal class Impl : IWritable {
    public Data Value { get; set; }
}

Impl.Value属性实现负责两者 IReadOnly.Value和IWritable.Value,如此测试片段所示:

The Impl.Value property implementation takes care of both IReadOnly.Value and IWritable.Value, as demonstrated in this test snippet:

        var obj = new Data();
        var target = new Impl();
        var irw = (IWritable)target;
        irw.Value = obj;
        var iro = (IReadOnly)target;
        System.Diagnostics.Debug.Assert(Object.ReferenceEquals(iro.Value, obj));

这篇关于将setter添加到派生接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆