Mat*_*ley 5 c# inheritance bittorrent data-structures
我想问的问题是:
是从一个可抽象的类,甚至是一个好的东西,从一个抽象类内部下来继承树(即,朝着一个更特殊的类),或者它总是一个可怜的选择,有更好的选择?
现在,举例说明为什么我认为它可以用得很好.
我最近在C#中使用BitTorrent协议实现了Bencoding.一个简单的问题,如何表示数据.我选择这样做,
我们有一个abstract BItem类,它提供了一些基本功能,包括static BItem Decode(string)用于将Bencoded字符串解码为必要结构的类.
还有四个派生类BString,BInteger,BList和BDictionary,表示待编码的四个不同的数据类型.现在,这是棘手的部分.BList并且分别BDictionary具有this[int]和this[string]访问器以允许访问这些数据类型的类似阵列的质量.
潜在的可怕部分现在即将到来:
BDictionary torrent = (BDictionary) BItem.DecodeFile("my.torrent");
int filelength = (BInteger)((BDictionary)((BList)((BDictionary)
torrent["info"])["files"])[0])["length"];
Run Code Online (Sandbox Code Playgroud)
嗯,你得到的照片......哎呀,这对眼睛很难,更不用说大脑了.所以,我在抽象类中引入了一些额外的东西:
public BItem this[int index]
{
get { return ((BList)this)[index]; }
}
public BItem this[string index]
{
get { return ((BDictionary)this)[index]; }
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以将旧代码重写为:
BDictionary torrent = (BDictionary)BItem.DecodeFile("my.torrent");
int filelength = (BInteger)torrent["info"]["files"][0]["length"];
Run Code Online (Sandbox Code Playgroud)
哇,嘿presto,更多可读代码.但是,我是否只是将我的灵魂的一部分用于将子类的知识隐含在抽象类中?
编辑:为了回应一些答案,你完全偏离了这个特定的问题,因为结构是可变的,例如我的例子torrent["info"]["files"][0]["length"]是有效的,但同样如此torrent["announce-list"][0][0],两者都将在90%的torrent文件中在那里.泛型不是要走的路,至少有这个问题:(.点击我链接的规格,它只有4个小点点大.
我想我会把这个[int]和这个[string]访问器虚拟化并在BList/BDictionary中覆盖它们.访问器没有意义的类应该强制转换NotSupportedException()(可能通过在BItem中使用默认实现).
这使得您的代码以相同的方式工作,并在您编写时提供更易读的错误
(BInteger)torrent["info"][0]["files"]["length"];
Run Code Online (Sandbox Code Playgroud)
因为失误.