是否可以为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; }
}
}
答案 0 :(得分:7)
不,重载的一条规则是重载只能通过返回值来区分。由于myBranch
可能是一个字典,因此它有时会返回string
,有时返回Branch
是没有意义的。我会写两个函数:
GetBranchByKey
和GetStringByKey
解决了过载问题。