c# - 如何*轻松*公开底层对象的方法?

标签 c# .net

假设我有一些定义如下的类:

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
}

然后我有另一个类包含上述类的实例。我怎样才能避免像下面这样的代码?我希望通过此类公开 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
}

编辑 我已将代码更新为更真实我正在做的事情。我在 Windows 服务中托管 WCF 服务。 Windows 服务做几件事,包括用户身份验证和与联网设备的通信等等。我的 WCF 接口(interface)的实现调用“MyWindowsService”类的方法。将底层对象作为属性公开是我一直在寻找的答案。上面的类看起来像这样:

class MyWindowsService
{
     SecurityClass _security = new SecurityClass();
     NetworkDevice _netDevice = new NetworkDevice();

     Public NetworkDevice NetDevice
     {
          get { return _netDevice; }
     }

     Public SecurityClass Security
     {
          get { return _security; }
     } 
}

最佳答案

好吧,如果您正在使用合成(就像现在一样),就没有“更简单的方法”;你只需要包装你想要公开的方法。如果您想公开组合类型的所有方法,那么为什么首先要使用组合?您也可以通过公共(public)属性公开 SecurityClassNetworkDevice,因为它在功能上与包装每个方法和属性/公共(public)字段没有什么不同。

如果它们属于继承链是有意义的,那么 SuperClass(奇怪的命名是因为它是一个子类...)应该从其中一个类继承。当然你不能在 C# 中继承两者,但这种设计让我怀疑可能有更好的整体方法。从您的代码示例中无法判断,因为您没有告诉我们您实际尝试使用这些类型完成什么。

关于c# - 如何*轻松*公开底层对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7490183/

相关文章:

c# - BindingExpression 路径错误 : property not found on 'object'

c# - 将两个包含属性的对象合并为一个对象

.net - 如果调用者忘记使用 Dispose(),如何释放不会被垃圾回收的托管资源?

c# - 委托(delegate)的目的

.net - 如何在旋转后而不是之前调整 WPF 元素的大小?

C# .NET 轨迹球支持 - 但不是作为鼠标!

c# - 通过本地路径而不是 TFS 路径在源代码管理资源管理器中导航

c# - 将任何给定的函数转换为可等待的任务

c# - 如何在 C# 中关闭 MessageBox 后强制按钮、文本框在窗体上重新绘制

c# - 避免 C# 中的递归事件