如何简化这个C#代码?

时间:2012-07-29 20:57:05

标签: c#

我想通过使用下面的语句得到一个字符串(str),它可以工作,但任何建议来制定这个控件? 因为伯爵可以是“n”。

 if (a.count== 0)
 {
    str += a.Name;
 }
    else if (a.count== 1)
 {
    str += a.Parent.Name + "/" +  a.Name;
 }
 else if (a.count== 2)
 {
    str += a.Parent.Parent.Name + "/" + a.Parent.Name + "/" + a.Name;
 }
 else if (a.count== 3)
 {
    str += a.Parent.Parent.Parent.Name + "/" +a.Parent.Parent.Name + "/" + a.Parent.Name + "/" + a.Name;
 }
 . 
 .
 .
 else if(a.count = n)
 {
         //n times..
 }

4 个答案:

答案 0 :(得分:4)

以下内容(但您需要使用它才能使其正常工作):

int count = a.count;
var current = a;
for (int i = 0; i <= count; i++)
{
    str += (i > 0 ? "/" : string.empty) + current.Name;
    current = current.Parent;
}

显然有很多极端情况需要考虑。

答案 1 :(得分:2)

如果在父级为空时停止,则可能不需要计数, 我认为使用Path.Combine更优雅:)

 var node = a;
 while (node != null) {
    str = Path.Combine(node.Name, str);
    node = node.Parent;
 }

或者您可以使用扩展方法为您计算:

 public static class Extension {

      public static string GetFullPath( this YourNodeType node)
      {
           return (node.Parent == null) 
             ? node.Name 
             : Path.Combine( node.Parent.GetFullPath(), node.Name);
      }
 }

答案 2 :(得分:1)

我会

  • 在A类型上创建一个返回自身及其父层次结构的枚举器
  • 使用LINQ选择Name-property
  • 反转()结果
  • 使用string.Join和斜杠来创建字符串

答案 3 :(得分:0)

你可以用这个:

object unknownparent;
for(int i = 0; i< n; i++)
{
unknownparent = a.Parent;
    for(int j = i; j<n; j++)
    {
        unknownparent = ((typeofa)unknownparent).Parent;
    }

    str += ((typeofa)unknownparent).Parent.Name + "/";

}
str += a.Name;