是否可以为该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; }
}
}
Run Code Online (Sandbox Code Playgroud)
不,重载的一个规则是Overloads只能通过返回值来区分.因为myBranch它可能是一本词典,所以它有时会返回一个string有时是一个有意义的词汇Branch.我会写两个函数:
GetBranchByKey并GetStringByKey解决过载问题.
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |