Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c# - How to deal with a sealed class when I wanted to inherit and add properties

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
}

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.

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

}

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.

Is there a better way to deal with this problem?

question from:https://stackoverflow.com/questions/2023769/how-to-deal-with-a-sealed-class-when-i-wanted-to-inherit-and-add-properties

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...