Der*_*erd 5 c# wpf inheritance sealed
我之所以这么问是因为我想创建一个具有 FileInfo 类(源自 FileInfo)的所有功能的类,并允许我向其中添加自己的属性。
我认为一个例子会更多地合作。我想要的是:
BindingList<FileInformation> files = new BindingList<FileInformation>();
public void GatherFileInfo(string path)
{
files.Add(new FileInformation(path));
listboxFiles.DataContext = files;
}
class FileInformation : FileInfo
{
public bool selected = false;
}
Run Code Online (Sandbox Code Playgroud)
对比我害怕我必须做的事情:
BindingList<FileInformation> files = new BindingList<FileInformation>();
public void GatherFileInfo(string path)
{
files.Add(new FileInformation(path));
listboxFiles.DataContext = files;
}
class FileInformation : FileInfo
{
string path = "<whatever>"
FileInfo fileInfo = new FileInfo(path);
public bool selected = false;
public string Name
{
get { return fileInfo.Name }
}
//Manually inherit everything I need???
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,在 WPF 中,您可以简单地绑定到 FileInformation 类的所有属性,包括继承的 FileInfo 类的属性。
我从来没有研究过这个问题,我也不知道应该从哪里开始寻找,所以一个关于如何做到这一点的例子或线索会有所帮助。
在.Net 中确实没有办法继承密封类。您可以编写扩展方法,但这不允许您添加新的属性或字段。您唯一可以做的另一件事是模拟继承,但是创建自己的类,其中包含要继承的类类型的字段,然后通过编写包装器手动公开“基”类的每个属性和方法每一种方法。如果班级规模小还好,但是如果班级规模大就很痛苦了。
我已经编写了代码生成器程序来使用反射自动为我完成此操作。然后我获取它的输出并扩展它。但这并不是真正的继承。我个人不喜欢密封类的概念,因为它阻止扩展这些类。但我认为他们这样做是出于性能原因。