如何处理密封类时,我想继承和添加属性 [英] How to deal with a sealed class when I wanted to inherit and add properties

查看:221
本文介绍了如何处理密封类时,我想继承和添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个最近的问题上堆栈溢出,我问我如何可能通过文件名有关文件的额外的元信息解析。

In a recent question on Stack Overflow, I asked how I might parse through a file name to extra meta info about a file.

在我经历了这个问题的工作,我决定,我可能要创建新的对象的类型来保存的元数据和原始文件。我想我可能会做这样的事情:

After I worked through that problem, I decided that I might want to create new type of object to hold the meta data and the original file. I thought I might do something like this:

class BackupFileInfo : FileInfo, IEquatable<BackupFileInfo>
{
    //Properties and Methods here
}



想法是,我会保留原来的的FileInfo 的对象,而在对象的属性加元信息实现的FileInfo IsMainBackup

The idea would be that I would retain the original FileInfo object while adding meta information in the properties of the object that implements FileInfo, such as IsMainBackup.

然而,的FileInfo 是密封的,这意味着其他类不能从它继承

However, FileInfo is sealed, which means other classes cannot inherit from it.

相反,我结束了以下内容:

Instead, I ended up with the following:

class BackupFileInfo : IEquatable<BackupFileInfo>
{
    public bool IsMainBackup { get; set; }
    public int ImageNumber { get; set; }
    public int IncrementNumber { get; set; }
    public FileInfo FileInfo { get; set; }

    //public BackupFileInfo() //constructor here

    public bool Equals(BackupFileInfo other)
    {
        return (this.FileInfo.Name == other.FileInfo.Name
             && this.FileInfo.Length == other.FileInfo.Length);
    }

}



我并不十分兴奋这个解决方案,因为不是能够使用 BackupFileInfo.Length ,我将不得不使用 BackupFileInfo.FileInfo.Length 。也许这是最好的做法了,但东西感觉不对。

I'm not terribly excited about this solution because instead of being able to use BackupFileInfo.Length, I'm going to have to use BackupFileInfo.FileInfo.Length. Perhaps this is the best practice already, but something doesn't feel right.

有没有一种更好的方式来处理这个问题?

推荐答案

这是一个经典的组合,而不是继承例子之一,你在正确的方向去了。

This is one of the classic composition instead of inheritance examples and you went in the right direction.

要解决你的财产问题,只需创建一个名为属性长度委托给封装的的FileInfo 对象。

To solve your property problem just create a property called Length that delegates to the encapsulated FileInfo object.

这篇关于如何处理密封类时,我想继承和添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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