The reason why I'm asking this is because I want to create a class that has all the functionality of the FileInfo class (derives from FileInfo), and allows me to add my own properties to it.
I Think an example will collaborate more. What I want:
BindingList<FileInformation> files = new BindingList<FileInformation>();
public void GatherFileInfo(string path)
{
files.Add(new FileInformation(path));
listboxFiles.DataContext = files;
}
class FileInformation : FileInfo
{
public bool selected = false;
}
Versus what I fear I must do:
BindingList<FileInformation> files = new BindingList<FileInformation>();
public void GatherFileInfo(string path)
{
files.Add(new FileInformation(path));
listboxFiles.DataContext = files;
}
class FileInformation : FileInfo
{
string path = "<whatever>"
FileInfo fileInfo = new FileInfo(path);
public bool selected = false;
public string Name
{
get { return fileInfo.Name }
}
//Manually inherit everything I need???
}
The advantage of this would be that in WPF you could simple bind to all the properties of the class FileInformation, including those of the inherited FileInfo class.
I've never looked into this matter and I have no lead to where I should start looking, so an example or a lead on how to do this would be helpful.
There really is no way to inherit from a sealed class in .Net. You can write extension methods, but this does not allow you to add new properties or fields. The only other thing you can do is to simulate inheritance, but making your own class that includes a field of the type of class you want to inherit from, and then manually expose each property and method of the "base" class by writing a wrapper method for each one. It's not bad if the class is small, but if it's a big class it becomes painful.
I've written code generator programs to use reflection to do this for me automatically. Then I take the output of that and extend it. But it's not true inheritance. I personally don't like the concept of sealed classes as it prevents extending those classes. But I suppose they did it for performance reasons.
To inherit from sealed class try using the Decorator design pattern, the basic idea is to create private instance of the OldClass, and implement manually all its methods like:
As
FileInfo
inherits fromMarshalByRefObject
, you can create a custom proxy that mimics aFileInfo
and handles all invocations in your own implementations. However, you wouldn't be able to cast that, and more importantly, you can't extend such class with custom properties. Anyway, should someone other want this, SharpUtils have some tools to assist with it.