简体   繁体   中英

Override a sealed classes toString

I have what I think is a simple question, but cannot find a simple answer.

I wanted to override the toString() method in System.IO.FileInfo ; however, my usual ways of doing this don't seem to work.

I had thought of creating a new class which inherited from System.IO.FileInfo , but I cannot do this because the method is defined as sealed public sealed class FileInfo : FileSystemInfo .

I tried creating a partial class; however, since System.IO is in a different assembly I wasn't able to get it to work properly.

I even considered creating an extension method, and while that worked for creating a new method I wasnt able to simply override toString() .


Essentially, in the currently implementation I have a listbox, and its items are a collection of FileInfo items. Currently the toString() just prints the name, but I wanted to have an entry with a little more information.

I understand a DataGridView would be more appropriate, but I don't really need multi-columns. I thought I could just set the ListBox's DisplayMember to my extension method... but, now I realize DisplayMember needs to point to a property... not a method.

Does anyone have any suggestions?

Thank you

You can not override them. You can write your own FileInfo -Class and implement all FileInfo methods in this class. Than you can write your own toString() method.

This would be the easiest solution:

public class OwnFileInfo
{
    private FileInfo fileInfo;

    public OwnFileInfo(string fileName)
    {
        fileInfo = new FileInfo(fileName);
    }

    public FileStream Create()
    {
        return fileInfo.Create();
    }

    // ... more methods
}

It is impossible to override the member of a sealed class. The whole point of sealing a class is to actively prevent anyone from overriding any of the members, allowing the type to rely on the exact implementations provided.

In your specific case the solution is to simply not bind objects of type FileInfo . Convert the collection of objects into something else (This can be as simple as a call to Enumerable.Select .), and bind that to your control, rather than binding the FileInfo objects directly.

Consider decorating the FileInfo class

public MyFileInfo 
{
   private FileInfo _fileInfo;

   public FileAttributes Attributes { get { return _fileInfo.Attributes; }  set { _fileInfo.Attributes = value; } }

   // other file info methods

   public override ToString()
   {
      // your code
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM