简体   繁体   English

如何在线性层次结构中实现迭代?

[英]How can I implement iterate in linear hierarchy?

I have this class ( interface):我有这个类(接口):

public interface IParentChiled
{
    IParentChiled Parent { get; }
    string Name { get; }
}

and there is method that should returns child's name prefixed with all its parents' names separated by the specified separator .并且有一个方法应该返回孩子的名字,前缀是所有父母的名字,由指定的 separator 分隔 something like : parent/child.类似的东西:父母/孩子。 the method is like this:方法是这样的:

 public string GetFullName(IParentChiled child, string separator = null)
 {
        separator ??= "/";
        throw new NotImplementedException();
 }

My Questions are :我的问题是:

1 . 1 . What is the name of this type of Class/Interface that use itself as property?这种将自身用作属性的类/接口的名称是什么?

2 . 2 . How can I impalement the Method?我怎样才能实施该方法?

To get a string like得到一个像这样的字符串

Root/Parent/Child

you can你可以

  1. Enumerate items (you can easily do it in Child, Parent, Root order).枚举项目(您可以轻松地按Child, Parent, Root顺序进行)。
  2. Reverse the enumeration. Reverse枚举。
  3. Join the items into the final string.将项目Join到最终字符串中。

Possible implementation:可能的实现:

using System.Linq;

...

// static: we don't want "this" in the method
public static string GetFullName(IParentChiled child, string separator = null) {
  // Enumerate Names but in reversed order      
  static IEnumerable<string> Items(IParentChiled last) {
    for (IParentChiled item = last; item != null; item = item.Parent)
      yield return item.Name;
  }

  return String.Join(separator ?? "/", Items(child).Reverse());
}

You can implement this as an extension method for the IParentChiled interface:您可以将其实现为IParentChiled接口的扩展方法

using System.Linq;

...

public static class ParentChiledExtensions {
  public static string GetFullName(this IParentChiled child, string separator = null) {
    // Enumerate Names but in reversed order      
    static IEnumerable<string> Items(IParentChiled last) {
      for (IParentChiled item = last; item != null; item = item.Parent)
        yield return item.Name;
    }

    return String.Join(separator ?? "/", Items(child).Reverse());
  }
}

Now you can use GetFullName method as if it's implemented by interface:现在您可以使用GetFullName方法,就好像它是由接口实现的一样:

IParentChiled item = ...

Console.Write(item.GetFullName("."));

there may be better solutions but i'd do something like this:可能有更好的解决方案,但我会做这样的事情:

public string GetFullName(IParentChiled child, string separator = null){
    separator ??= "/";
    var parent = child;
    string name = child.name;
    while(parent.parent!=null){
        parent = parent.parent;
        name = parent.name + separator + name;
    }
    return name;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM