两个定义为'这个'方法

时间:2014-06-17 00:43:15

标签: c# method-overriding

是否可以为this方法设置2个定义?我希望用户能够执行以下两项操作:string value = myBranch[stringKey];Branch child = myBranch[stringKey]

这可能吗?如果没有,你能否建议我如何设计我的班级以实现相同的外部互动(即,轻松访问子分支或价值)?

public class Branch {
    public enum BranchType  {TYPE_BRANCH, TYPE_LEAF}
    private string key                              = null;
    private string value                            = null;
    private Branch parent                           = null;
    private Dictionary <string, Branch> children    = new Dictionary <string, Branch>();

    // Is it possible to have 2 'this' definitions?
    // Def 1:
    public Branch this[string attribKey] {
        get
        {
            if (this.children.ContainsKey(attribKey))
                return this.children[attribKey];

            return Branch.EmptyBranch;
        }
        set
        {
            children[attribKey] = value;
            value.Parent        = this;
            this.Type           = BranchType.TYPE_BRANCH;
        }
    }

    // Def 1:
    public string this[string attribKey] {
        get 
        { 
            return value; 
        }   
        set 
        {
            value = value;
        }
    }

    public string Key {
        get { return key; }
    }
}

1 个答案:

答案 0 :(得分:7)

不,重载的一条规则是重载只能通过返回值来区分。由于myBranch可能是一个字典,因此它有时会返回string,有时返回Branch是没有意义的。我会写两个函数:

GetBranchByKeyGetStringByKey解决了过载问题。