我有这样一个类(接口):
public interface IParentChiled
{
IParentChiled Parent { get; }
string Name { get; }
}
并且有一个方法返回子节点的名字前缀,所有父节点的名字由指定的分隔符分隔. 比如:parent/child。方法如下:
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());
}
作为<<p>你可以实现这个em>扩展方法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;
}