假设有以下接口
public interface IRoot
{
IChildA ChildA { get; }
IChildB ChildB { get; }
}
public interface IChildA
{
IGrandChildA GrandChildA { get; }
IGrandChildB GrandChildB { get; }
}
public interface IChildB
{
IGrandChildC GrandChildC { get; }
}
public interface IGrandChildA
{
}
public interface IGrandChildB
{
}
public interface IGrandChildC
{
}
我想写一个流畅的'配置器'来保持接口关联。一切都应该是这样的:
private static void Test()
{
Configurator.Root<IRoot>()
.Join( _ => _.ChildA )
.Join( _ => _.GrandChildA )
.Up()
.Join( _ => _.GrandChildB )
.Up()
.Up()
.Join( _ => _.ChildB );
}
需要允许任意嵌套级别的Join / Up对。这是我尝试声明这样的配置器。
public static class Configurator
{
public static IConfigBuilder<T, T> Root<T>()
{
return null;
}
}
public interface IConfigBuilder<P, T>
{
IConfigBuilder<T, C> Join<C>( Expression<Func<T, C>> expression );
IConfigBuilder<???, P> Up(); // This is the problem. How can I get grand-parent type?
}
我不清楚如何记住所有前面的节点类型。换句话说,如何声明Up()
方法?这让我想起了古老的Alexandrescu在C ++中的类型列表。有没有办法在.net中实现相同的目标?
答案 0 :(得分:2)
您至少需要两个接口;而不是为IConfigBuilder<...>
返回Up
,相信创建代码以了解它创建的内容:
public interface IConfigBuilder<T>
{
IConfigBuilder<IConfigBuilder<T>, C> Join<C>(Expression<Func<T, C>> expression);
}
public interface IConfigBuilder<P, T> : IConfigBuilder<T>
{
P Up(); // This is the problem. How can I get grand-parent type?
new IConfigBuilder<IConfigBuilder<P, T>, C> Join<C>(Expression<Func<T, C>> expression);
}