Csharp/C#教程:是否有inheritance密封类的替代方法?分享


是否有inheritance密封类的替代方法?

我问这个的原因是因为我想创建一个具有FileInfo类的所有function的类(从FileInfo派生),并允许我添加自己的属性。

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

BindingList files = new BindingList(); public void GatherFileInfo(string path) { files.Add(new FileInformation(path)); listboxFiles.DataContext = files; } class FileInformation : FileInfo { public bool selected = false; } 

与我害怕我必须做的事情:

 BindingList files = new BindingList(); public void GatherFileInfo(string path) { files.Add(new FileInformation(path)); listboxFiles.DataContext = files; } class FileInformation : FileInfo { string path = "" FileInfo fileInfo = new FileInfo(path); public bool selected = false; public string Name { get { return fileInfo.Name } } //Manually inherit everything I need??? } 

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

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

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

我编写了代码生成器程序来使用reflection来自动为我做这件事。 然后我取出它的输出并扩展它。 但这不是真正的inheritance。 我个人不喜欢密封类的概念,因为它阻止了扩展这些类。 但我想他们出于性能原因这样做了。

要从密封类inheritance尝试使用Decorator设计模式,基本思想是创建OldClass的私有实例,并手动实现其所有方法,如:

 public class NewClass { private OldClass oldClass = new OldClass(); public override string ToString() { return oldClass.ToString(); } //void example public void Method1() { oldClass.Method1(); } //primitive type example public int Method2() { return oldClass.Method2(); } //chaining example, please note you must return "this" and (do not return the oldClass instance). public NewClass Method3() { oldClass.Method3(); return this; } } public class Demo { static void Main(string[] args) { var newClass = new NewClass(); newClass.Method3(); WriteLine(newClass); } } 

由于FileInfoinheritance自MarshalByRefObject ,您可以创建一个模仿FileInfo的自定义代理,并处理您自己的实现中的所有调用。 但是,您无法强制转换它,更重要的是,您无法使用自定义属性扩展此类。 无论如何,如果其他人想要这个, SharpUtils有一些工具可以帮助它。

上述就是C#学习教程:是否有inheritance密封类的替代方法?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/959683.html

(0)
上一篇 2021年11月24日
下一篇 2021年11月24日

精彩推荐