覆盖和调用基属性设置方法

本文关键字:设置 方法 属性 调用 覆盖 | 更新日期: 2023-09-27 18:17:19

是否可以重写属性,但也调用基本属性设置方法?

例如

;在类Child中,我想覆盖this[]操作符,但也调用基础this[]操作符?

public class Base {
    protected Branch properties = Branch.EmptyBranch; 
    public virtual Branch this[string attribKey] {
        get
        {
            return properties[attribKey]; // will return Branch.EmptyBranch if key doesn't exist
        }
        set
        {
            properties[attribKey] = value;
        }
    }
}
public class Child {
    protected uint dimensions = 3;
    public override Branch this[string attribKey] {
        // No need to override get as we dont have any custom functionality
        set
        {
            // Can I call the base 'set' method?
            base[attribKey];
            // Add custom functionality
            if (attribKey.Equals("data_2d"))
                dimensions = 2;
        }
    }
}

覆盖和调用基属性设置方法

你可以像这样调用base set方法,它应该不会引起任何问题:

public override Branch this[string attribKey] {
        set
        {                
            base[attribKey] = value;    
            if (attribKey.Equals("data_2d"))
                dimensions = 2;
        }
    }