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

前端 未结 6 1401
慢半拍i
慢半拍i 2020-12-15 15:15

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

相关标签:
6条回答
  • 2020-12-15 15:55

    You could add an implicit operator to your class.

    Eg:

    class BackupFileInfo .... {
      /* your exiting code */
    
      public static implicit operator FileInfo( BackupFileInfo self ){
         return self.FileInfo;
      }
    }
    

    You could then treat your BackupFileInfo object like a FileInfo object like so

    BackupFileInfo bf = new BackupFileInfo();
    ...
    int mylen = ((FileInfo)bf).Length;
    
    0 讨论(0)
  • 2020-12-15 16:04

    You can easily wrap the file info properties in your own properties if you like.

    public long Length
    {
        get
        {
           return this.FileInfo.Length;
        }
    }
    
    0 讨论(0)
  • 2020-12-15 16:05

    You could just expose the properties on FileInfo you care about. Something like this:

    public long Length { get { return FileInfo.Length; } }
    

    This obviously becomes less practical if you want to delegate a lot of properties to FileInfo.

    0 讨论(0)
  • 2020-12-15 16:05

    Pass-thru?

    class BackupFileInfo : IEquatable<BackupFileInfo>
    {
        public long Length {get {return FileInfo.Length;}}
        //.... [snip]
    }
    

    Also, a prop called FileInfo is asking for trouble... it may need disambiguation against the FileInfo class in a few places.

    0 讨论(0)
  • 2020-12-15 16:15

    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.

    0 讨论(0)
  • 2020-12-15 16:16

    This doesn't really solve your larger problem, but of course you can just make the properties you want to use act as proxies to the real properties underneath. E.g.

    public long Length
    {
        get {return FileInfo.Length;}
    }
    

    (With approriate null-checking of course.)

    0 讨论(0)
提交回复
热议问题