问题描述
是否有可能以某种方式在 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; }
}
我希望能够向外部程序集公开只读接口,但在内部使用可写接口(我也可以通过不同方式实现).
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 添加到派生接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!