簡體   English   中英

有繼承密封類的替代方法嗎?

[英]Is there an alternative to inheriting from sealed classes?

我問這個的原因是因為我想創建一個具有FileInfo類的所有功能的類(派生自FileInfo),並允許我添加自己的屬性。

我認為一個例子會更多地合作。 我想要的是:

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

與我害怕我必須做的事情:

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???
}

這樣做的好處是,在WPF中,您可以簡單地綁定到FileInformation類的所有屬性,包括繼承的FileInfo類的屬性。

我從來沒有調查過這個問題,而且我沒有引導到我應該開始尋找的地方,所以一個例子或如何做到這一點的主角將是有幫助的。

真的沒有辦法從.Net中的密封類繼承。 您可以編寫擴展方法,但這不允許您添加新屬性或字段。 您可以做的唯一其他事情是模擬繼承,但是創建自己的類,其中包含您要繼承的類類型的字段,然后通過編寫包裝器手動公開“基類”的每個屬性和方法每個人的方法。 如果班級很小,那也不錯,但如果它是一個大班,那就會變得很痛苦。

我已經編寫了代碼生成器程序來使用反射來自動執行此操作。 然后我取出它的輸出並擴展它。 但這不是真正的繼承。 我個人不喜歡密封類的概念,因為它阻止了擴展這些類。 但我想他們出於性能原因這樣做了。

要從密封類繼承嘗試使用Decorator設計模式,基本思想是創建OldClass的私有實例,並手動實現其所有方法,如:

public class NewClass
{
    private OldClass oldClass = new OldClass();

    public override string ToString() 
    {
        return oldClass.ToString();
    }
    //void example
    public void Method1()
    {
        oldClass.Method1();
    }
    //primitive type example
    public int Method2()
    {
        return oldClass.Method2();
    } 
    //chaining example, please note you must return "this" and (do not return the oldClass instance).
    public NewClass Method3()
    {
        oldClass.Method3();
        return this;
    }
}

public class Demo
{
    static void Main(string[] args)
    {
       var newClass = new NewClass();
       newClass.Method3();
       WriteLine(newClass);
    }
}

由於FileInfo繼承自MarshalByRefObject ,您可以創建一個模仿FileInfo的自定義代理,並處理您自己的實現中的所有調用。 但是,您無法強制轉換,更重要的是,您無法使用自定義屬性擴展此類。 無論如何,如果其他人想要這個, SharpUtils有一些工具可以幫助它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM