c# - 如何重写 TreeNodeCollection.Add(TreeNode)?

标签 c# .net winforms treeview

我有这个:

public abstract class DRT_Tvw_Abstract : TreeView
{
    TableCountMetrics metrics;
    public TableCountMetrics Metrics { get => metrics; set => metrics = value; }

    public class TableCountMetrics
    {
        int schemaNameCount = 0;
        int tableNameCount = 0;

        public int SchemaNameCount { get => schemaNameCount; set => schemaNameCount = value; }
        public int TableNameCount { get => tableNameCount; set => tableNameCount = value; }
    }

    public DRT_Tvw_Abstract() : base()
    {
    }
}

public class DRT_Tvw_TableList_Unfiltered : DRT_Tvw_Abstract
{
    public DRT_Tvw_TableList_Unfiltered() : base()
    {
    }

    public void _CreateTreeView(DataTable dataTable)
    {
        tableListTreeViewNode = new {treeview node from my class that derives from TreeNode}

        Nodes.Add(tableListTreeViewNode);       
}

我想要做的是覆盖 Add 方法,以便我可以递增/递减属于我的 DRT_Tvw_Abstract 类的自定义整数属性同时我添加一个TreeNode。我首先尝试从 TreeNodeCollection 类派生,但这似乎是一个死胡同,因为我无法弄清楚 TreeNodeCollection 类的有效 ctor 是什么

Nodes(如Nodes.Add)是一个属性。如何从中派生以便重写 Add 方法?我首先为此 poprperty 创建一个覆盖,但我不知道如何从属性覆盖代码中覆盖方法 (Add)。

public new virtual TreeNodeCollection Nodes
{

    //override the Add method from within here somehow?

    get
    {
        return base.Nodes;
    }

    set
    {
    }
}

重写 TreeNodeCollection 类 Add(TreeNode) 方法的语法是什么?

最佳答案

Add方法属于TreeNodeCollection类(class)。如果您希望使用带有新签名的新 Add 方法:

  • 当然,您可能会考虑从 TreeNodeCollection 派生并定义新方法,并从 TreeView 派生并将其 TreeNodeCollection 替换为您的新方法自定义节点集合。但不要尝试这个解决方案。 TreeNodeCollection 没有公共(public)构造函数。所以我建议创建 Extension Methods .

  • 您可能想到的另一个解决方案是从 TreeView 派生,并向派生的 TreeView 添加新的 Add 方法。

示例 - 扩展方法

新建一个代码文件,复制以下代码并粘贴到代码文件中:

namespace MyExtensions
{
    using System.Windows.Forms;
    public static class TreeNodeCollectionExtensions
    {
        //Just an example of a new signature, use the signature that you need instead:
        public static TreeNode Add(this TreeNodeCollection nodes, string text, int tag)
        {
            var node = nodes.Add(text);
            node.Tag = tag;
            return node;
        }
    }
}

然后在您要使用新的 Add 方法的类中,首先添加 using 语句:

using MyExtensions;

然后像普通方法一样使用它:

treeView1.Nodes.Add("One", 1);

关于c# - 如何重写 TreeNodeCollection.Add(TreeNode)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51089409/

相关文章:

c# - 如何在 C# 中链接 XY 条形图中的两个 sql 列

c# - 使用多线程与 C# 进行 OCR

c# - BasicHttpBinding 和 MessageVersion.None

.net - 具有某些特殊字符的密码的正则表达式,不包括所有其他字符

c# - Process.Kill() 和进程事件

c# - DPI 意识 - 在一个版本中没有意识到,在另一个版本中有系统意识

c# - 绑定(bind)属性以在 Winforms 中进行控制

c# - OWIN 托管的 web api : using windows authentication and allow anonymous access

c# - 检测 Windows 错误/弹出窗口

C#,无法将 .p7b 证书导入 Windows 应用商店