假设我有一些类定义如下:
class Security
{
Boolean AuthenticateUser(String username, String password);
Boolean AddUser(String username, String password);
// many more methods
}
class NetworkedDevice
{
void Stop();
void Start();
// many more methods
}
Run Code Online (Sandbox Code Playgroud)
然后我有另一个包含上述类的实例的类.如何避免以下代码?我希望通过这个类公开class1和class2的所有方法.
class MyWindowsService
{
Security _security = new Security();
NetworkDevice _netDevice = new NetworkDevice();
Boolean AuthenticateUser(String username, String password)
{
return _security.AuthenticateUser(username, password);
}
// all the rest of "Security" methods implemented here
void StopNetworkDevice()
{
_netDevice.Stop();
}
void StartNetorkDevice()
{
_netDevice.Start();
}
// all the rest of "NetDevice" methods implemented here
}
Run Code Online (Sandbox Code Playgroud)
编辑 我已经更新了代码,使其更加真实.我在Windows服务中托管WCF服务.Windows服务可以执行多项操作,包括用户身份验证和与联网设备的通信等等.我的WCF接口的实现调用了"MyWindowsService"类的方法.将底层对象公开为属性是我正在寻找的答案.上面的类看起来像:
class MyWindowsService
{
SecurityClass _security = new SecurityClass();
NetworkDevice _netDevice = new NetworkDevice();
Public NetworkDevice NetDevice
{
get { return _netDevice; }
}
Public SecurityClass Security
{
get { return _security; }
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,如果你正在使用作曲(就像你一样),没有"更简单的方法"; 你只需要包装你想要公开的方法.如果要公开组合类型的所有方法,那么为什么首先使用组合?您也可以公开oneClass并twoClass通过公共属性,因为它在功能上与包装每个方法和属性/公共字段没有什么不同.
如果它们属于继承链是有意义的,那么SuperClass(奇怪地命名为它将是一个子类......)应该继承其中一个类.当然你不能从C#继承,但这种设计让我怀疑可能有更好的整体方法.虽然您没有告诉我们您使用这些类型实际尝试完成的内容,但您无法从代码示例中分辨出来.
| 归档时间: |
|
| 查看次数: |
2003 次 |
| 最近记录: |