使用 C# 我有一个现有接口(interface),我希望将其拆分为读取和写入接口(interface),但仍保留原始接口(interface)。什么是最好的方法?
我可以制作 3 个独立的界面:
interface IExistingReadWrite{
int width {get; set;}
}
interface IRead{
int width {get;}
}
interface IWrite{
int width {set;}
}
或者我可以使 IExistingReadWrite 继承自 IRead 和 IWrite,这样其他编码人员在查看 IExistingReadWrite 时会更清楚,也可以使用隔离的 IRead 和 IWrite 接口(interface)...
interface IExistingReadWrite: IRead, IWrite{
new int width {get; set;}
}
interface IRead{
int width {get;}
}
interface IWrite{
int width {set;}
}
但我现在不得不在 IExistingReadWrite 上使用“new”来隐藏 IRead 和 IWrite 中的属性,否则会出现关于歧义的警告。阴影并不是我真正的意图我希望 IExistingReadWrite 将工作“传递”到它继承的接口(interface)而不是定义一个新属性(因此没有机会为每个单独的接口(interface)进行单独的实现)。有没有更好的办法。
最佳答案
看起来 Corak 到目前为止有最好的答案......放弃继承 IExistingReadWrite 上的 IWrite 接口(interface),所以现在的解决方案看起来......
interface IExistingReadWrite : IRead
{
// Use IWrite interface instead if you require write only.
int width { get; set; }
}
interface IRead
{
int width { get; }
}
public interface IWrite
{
int width {set; }
}
这给出了 OK 行为。如果您需要更高的安全性,您可以添加一个适配器,例如:
internal class WriteImpl : IWrite
{
private IExistingReadWrite worker;
internal FooWriteImpl(IExistingReadWrite i)
{
worker = i;
}
public string width
{
get { throw new Exception("Dave I cannot let you do that");}
set { worker.width = value; }
}
}
关于c# - 我有一个现有的接口(interface)(带有属性)什么是隔离读写的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46162949/