C#:如何从基本 class 属性中导出新属性的值?

C#: how can I derive the value of new attribute from the base class attribute?

我想为树节点对象添加一个属性。

我希望新的属性值(即键)来自 Treenode.Fullpath。

我该如何实施?

class ItemNode:TreeNode
{
    internal string key  { get; set; } = base.FullPath.split("\")[1]; //Error
} 

在初始化字段时无法计算该值。太早了。该对象仍在构造中,编译器无法确定基础部分是否处于有效状态,因此不允许访问其数据。

我建议您自己实现 属性 以便您可以控制逻辑何时执行。然后你可以随时加载它。例如,一个简单的延迟加载可以像这样工作:

class ItemNode:TreeNode
{
    internal private string _key = null;

    internal public string Key
    {
        get
        {
            if (_key == null) _key = base.FullPath.split("\")[1];
            return _key;
        }
        set 
        {
            _key = value;
        }
     }
}