我正在尝试简化正在构建的服务器上的Send函数。我想通过发送数据来减少发送数据的方法的数量,以便在参数中指定发送的信息。
例如,从许多类似的方法中获取:
public static void QueryUsername( string text )
{
PacketBuffer buffer = new PacketBuffer();
buffer.Write( Outbound.DoesUserExist );
buffer.Write( text );
ClientTCP.SendData( buffer.ToArray() );
buffer.Dispose();
}
对于这样的单个方法:
public static void Send( Outbound packageIndex, params object[] parameter )
{
PacketBuffer buffer = new PacketBuffer();
buffer.Write( packageIndex );
foreach ( object item in parameter )
{
buffer.Write( item );
}
ClientTCP.SendData( buffer.ToArray() );
buffer.Dispose();
}
I'm having difficulty figuring out how to pass the parameter
data through the Write
method though.
有人对我如何实现这一目标有任何建议吗?
The Write
method has 5 overloads that transform different types into bytes so they can be packaged and sent between the client and server.
To do exactly what you are asking, you will need to use reflection to look up the appropriate method, based on the type of the provided argument(s). See e.g. How can I programmatically do method overload resolution in C#?.
Note that reflection is very slow. If you're going to take this route, you will probably want to at least memoize the
MethodInfo
object for each parameter type you come across, and more likely you'll want to memoize an actual delegate instance representing the method (e.g. usingExpression
to build the delegate).另一种方法是在代码中手动创建代表字典。这是实现目标的简单得多的方法,但存在忽略支持的方法的风险。您需要确保字典包含期望的每种参数类型的条目,如果以后添加了新类型,则必须记住将其添加到字典中。
话虽如此,我建议不要这样做。我不知道您现在有多少种方法,但事实是它们准确反映了网络API的复杂性。只需查看已实现的方法,即可轻松查看代码并查看协议支持的所有内容。同时查看每种协议方法的参数是很简单的,也许最重要的是,C#类型系统为您提供了每个调用站点正确性的编译时保证。
如果切换到基于反射的方法,则将失去所有这些可改善代码可维护性和可靠性的功能。每个调用方都将仅“知道”要传递的正确参数,并且编译器将不会帮助您确保它们传递正确的参数。而且代码也将更难阅读。
如果您发现API中的方法数量超过了一定的舒适度阈值,则可能需要考虑是否需要重新设计API本身,方法是添加新的端点,或者通过构造API中的方法以包含某种形式的方法。有助于更好地组织它们的层次结构。我不认为更改API的实现是正确的方法。确实,我敢肯定不是。 :)