是否有继承密封类的替代方法? [英] Is there an alternative to inheriting from sealed classes?

查看:307
本文介绍了是否有继承密封类的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之所以这样问,是因为我想创建一个具有FileInfo类所有功能的类(派生自FileInfo),并允许我向其添加自己的属性。

The reason why I'm asking this is because I want to create a class that has all the functionality of the FileInfo class (derives from FileInfo), and allows me to add my own properties to it.

我认为一个例子会更多地合作。
我想要的是什么:

I Think an example will collaborate more. What I want:

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;
}

我担心必须做的事情:

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???
}

这样做的好处是在WPF中你可以简单地绑定到所有的FileInformation类的属性,包括继承的FileInfo类的属性。

The advantage of this would be that in WPF you could simple bind to all the properties of the class FileInformation, including those of the inherited FileInfo class.

我从来没有调查过这个问题而且我没有引导到我应该开始寻找的地方,所以关于如何做到这一点的一个例子或者领导会很有帮助。

I've never looked into this matter and I have no lead to where I should start looking, so an example or a lead on how to do this would be helpful.

推荐答案

真的没有办法从密封的类继承在.Net。您可以编写扩展方法,但这不允许您添加新属性或字段。您可以做的唯一其他事情是模拟继承,但是创建自己的类,其中包含要继承的类类型的字段,然后通过编写包装器手动公开基类的每个属性和方法每个人的方法。如果班级很小,那也不错,但如果这是一个大班,那就太痛苦了。

There really is no way to inherit from a sealed class in .Net. You can write extension methods, but this does not allow you to add new properties or fields. The only other thing you can do is to simulate inheritance, but making your own class that includes a field of the type of class you want to inherit from, and then manually expose each property and method of the "base" class by writing a wrapper method for each one. It's not bad if the class is small, but if it's a big class it becomes painful.

我编写了代码生成器程序,使用反射自动为我完成此操作。然后我取出它的输出并扩展它。但这不是真正的继承。我个人不喜欢密封类的概念,因为它阻止了扩展这些类。但我认为他们出于性能原因这样做了。

I've written code generator programs to use reflection to do this for me automatically. Then I take the output of that and extend it. But it's not true inheritance. I personally don't like the concept of sealed classes as it prevents extending those classes. But I suppose they did it for performance reasons.

这篇关于是否有继承密封类的替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆