[英]How can I implement iterate in linear hierarchy?
我有这个类(接口):
public interface IParentChiled
{
IParentChiled Parent { get; }
string Name { get; }
}
并且有一个方法应该返回孩子的名字,前缀是所有父母的名字,由指定的 separator 分隔。 类似的东西:父母/孩子。 方法是这样的:
public string GetFullName(IParentChiled child, string separator = null)
{
separator ??= "/";
throw new NotImplementedException();
}
我的问题是:
1 . 这种将自身用作属性的类/接口的名称是什么?
2 . 我怎样才能实施该方法?
得到一个像这样的字符串
Root/Parent/Child
你可以
Child, Parent, Root
顺序进行)。Reverse
枚举。Join
到最终字符串中。可能的实现:
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());
}
您可以将其实现为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());
}
}
现在您可以使用GetFullName
方法,就好像它是由接口实现的一样:
IParentChiled item = ...
Console.Write(item.GetFullName("."));
可能有更好的解决方案,但我会做这样的事情:
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.