【发布时间】:2010-09-24 18:03:41
【问题描述】:
对于一个有趣的项目,我正在尝试实施 BitTorrent 规范,现在我正在研究它的 BEncoding 部分。
编码基本上可以从int/string/dictionary -> string进行编码进行传输。我已经编写/测试了所有不同的编码/作为重载的 Encode(...) 方法工作,并且我已经编写/测试了/作为 DecodeString(...)、DecodeInt(...) 工作的各个解码方法) 等。
我想不出一种方法让所有解码都使用 1 种解码方法,以使编码/解码的 API 尽可能干净(暂时是 2 种公共方法)。
请注意,我有一个方法可以获取解码后的字符串将具有的结果类型。
客户端代码,现在每次他们想要解码消息时都必须看起来像这样:
string s = ...; // Encoded string
Type t = Encoder.GetDecodedType(s);
if (t == typeof(int))
process(Encoder.DecodeInt(s));
else if (t == typeof(string))
process(Encoder.DecodeString(s));
else if (t == typeof(Dictionary<string, string>))
process(Encoder.DecodeStringDictionary(s));
else if (t == typeof(Dictionary<string, int>))
process(Encoder.DecodeIntDictionary(s)):
我希望能够将其清理得更像:
string s = ...; // Encoded string
process(Encoder.Decode(s));
在这两种情况下,process(...) 都可能是客户端的重载函数,采用 4 种类型的解码值。
【问题讨论】:
标签: c# design-patterns api oop