Eam*_*nne 29 c# inheritance design-patterns interface
我有一组接口,用于与特定的可变对象紧密结合.
该对象的许多用户只需要能够从对象中读取值,然后只需要几个属性.为了避免命名空间污染(更容易智能感知)和跨越使用意图,我希望有一个小的基本接口,它只以只读方式暴露一些"关键"属性.
但是,几乎所有实现都将支持完整的界面,其中包括可修改性.
不幸的是,我遇到了在C#中表达这个概念的障碍:
interface IBasicProps {
public int Priority { get; }
public string Name {get;}
//... whatever
}
interface IBasicPropsWriteable:IBasicProps {
public int Priority { set; } //warning CS0108: [...] hides inherited member [...]
public string Name { set; }
//... whatever
}
Run Code Online (Sandbox Code Playgroud)
我当然不打算隐藏任何成员,所以不好!
当然,我可以使用方法解决这个问题,但是什么是正确的选择?我想保持"核心"接口尽可能小,即使分割接口除了传递意图之外没有任何其他目的.在拆分接口,它只是真的很明显哪些方法不会做任何更新,这让编写代码更清楚一点(何况还可以很好的正简单的静态单存根足够了好几个简单的情况下) .
我想避免任何抽象类等; 他们重新实现或快速单一用途垫片更复杂和难以理解.
那么,想法?
Mar*_*ell 29
隐藏在界面中的方法几乎不那么蹩脚; 我会选择以下内容:
interface IBasicProps {
int Priority { get; }
string Name {get;}
//... whatever
}
interface IBasicPropsWriteable:IBasicProps {
new int Priority { get; set; }
new string Name { get; set; }
//... whatever
}
class Foo : IBasicPropsWriteable {
public int Priority {get;set;}
public string Name {get;set;}
/* optional
int IBasicProps.Priority {get {return Priority;}}
string IBasicProps.Name {get {return Name;}}
*/
}
Run Code Online (Sandbox Code Playgroud)
如果您的目标是在允许读取和写入时使其更加清晰,那么我将使用单独的 getter 和 setter 方法而不是属性。
interface IBasicProps {
int GetPriority();
string GetName();
//... whatever
}
interface IBasicPropsWriteable:IBasicProps {
void SetPriority(int priority);
void SetName(string name);
//... whatever
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19442 次 |
| 最近记录: |