gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:27:33 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com