为了一个有趣的项目,我正在尝试实现 BitTorrent 规范,现在我正在研究它的 BEncoding 部分。
编码基本上可以从int/string/dictionary -> string进行编码进行传输。我已经将所有不同的编码编写/测试/工作为重载的 Encode(...) 方法,并且我已经将各个解码方法编写/测试/工作为 DecodeString(...)、DecodeInt(... ) 等
我想不出一种方法让所有解码都有 1 个 Decode 方法,以保持编码/解码的 API 尽可能干净(暂时有 2 个公共(public)方法,最重要的)。
请注意,我有一个方法可以获取解码字符串将具有的结果类型。
客户端代码,现在每次他们想要解码消息时都必须看起来像这样:
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 种类型的解码值。
请您参考如下方法:
您可以让 DLR 为您做这件事。
public static void Process(int i) { ... }
public static void Process(string s) { ... }
public static void Process(Dictionary<string, string> dic) { ... }
public static void Process(Dictionary<string, int> dic) { ... }
[...]
public dynamic Decode(string input) // or 'object' if you prefer
{
var t = GetDecodedType(input);
if (t == typeof(int))
return DecodeInt(input);
else if (t == ...)
// ...
}
[...]
string s = ...; // Encoded string
Process(Encoder.Decode(s)); // if you used 'dynamic' above
Process((dynamic)Encoder.Decode(s)); // if you used 'object' above
