[英]What should you do if you have an interface with a collection of objects and you want both a read-only and a read-write version of the interface?
I'm currently creating some interfaces for user controls that will contain collections of objects. 我目前正在为用户控件创建一些界面,这些界面将包含对象的集合。 I want to have an interface for a control that can have objects added from the outside, and another interface for one that cannot have objects added from the outside. 我想为一个控件提供一个接口,该控件可以从外部添加对象,而另一个控件为不能从外部添加对象的接口。 So far I basically have the following (simplified for this question; if it would help you to see the actual code I have thus far please let me know): 到目前为止,我基本上有以下内容(简化此问题;如果可以帮助您查看到目前为止我拥有的实际代码,请告诉我):
public interface IReadableFoo
{
IReadOnlyCollection<Foo> Foos { get; }
}
public interface IReadWriteFoo : IReadOnlyFoo
{
new ICollection<Foo> Foos { get; }
}
What is considered the "best practice" to do in this situation where you have an interface with a collection of objects, and you want to have both a read-only version and a read-write version? 在这种情况下,如果您具有一个带有对象集合的接口并且想要同时拥有只读版本和读写版本,那么被认为是“最佳实践”? Is it considered acceptable to have an ICollection<Foo>
shadowing an IReadOnlyCollection<Foo>
like that? 像这样IReadOnlyCollection<Foo>
的ICollection<Foo>
是否被认为可以接受?
Is there some other pattern I should be using instead? 还有其他我应该使用的模式吗? Should IReadOnlyFoo
and IReadWriteFoo
both inherit from a common base interface IFoo
? IReadOnlyFoo
和IReadWriteFoo
是否IReadWriteFoo
从通用基本接口IFoo
继承?
Edit: To clarify what I am trying to do, I'm adding the actual code that I'm working with here: 编辑:为了澄清我要做什么,我在这里添加正在使用的实际代码:
public interface IOptionSelector<T>
{
IReadOnlyCollection<T> Options { get; }
T SelectedOption { get; }
event EventHandler SelectedOptionChanged;
}
public interface IWriteableOptionSelector<T> : IOptionSelector<T>
{
new ICollection<T> Options { get; }
new T SelectedOption { get; set; }
}
Here is what you should do: 这是您应该做的:
public interface IOptionSelector<T>
{
event EventHandler SelectedOptionChanged;
}
public interface IReadOnlyOptionSelector<T> : IOptionSelector<T>
{
IReadOnlyCollection<T> Options { get; }
}
public interface IWritableOptionsSelector<T> : IOptionSelector<T>
{
ICollection<T> Options { get; }
}
ReadOnly and Writeable are two separate concerns. ReadOnly和Writeable是两个单独的问题。 When you have to use the new keyword on methods that you wrote that is a clear indication that you are dealing with separate concerns and need to rethink your design. 当您必须在编写的方法上使用new关键字时,这清楚地表明您正在处理单独的问题,需要重新考虑设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.