[英]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你可以
Child, Parent, Root
order).Child, Parent, Root
顺序进行)。Reverse
the enumeration. Reverse
枚举。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.