繁体   English   中英

C#:如何从基类属性中导出new属性的值?

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

我想向treenode对象添加一个属性。

我希望新的属性值(即键)派生自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;
        }
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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