代码之家  ›  专栏  ›  技术社区  ›  ctorx

嵌套Lambda用于Fluent接口

  •  2
  • ctorx  · 技术社区  · 17 年前

    class Parent { List<Child> Children {get;set;}}
    class Child {List<Child> GrandChildren {get;set;}}
    
    class Helper<TEntity> {List<string> Properties {get;set;}}
    

    public Helper AddProps<TEntity, TProp>(Expression<Func<TEntity, TProp>> exp)
    {
         this.Properties.Add(GetPropInfo(exp).Name);
    }
    
    public PropertyInfo GetPropInfo(Expression<Func<TEntity, TProp>> exp)
    {
         return (PropertyInfo)((MemberExpression)(expression.Body)).Member;
    }
    

    我能够做到这一点:

    Helper<Parent> myHelper = new Helper<Parent>();
    myHelper.AddProps(x => x.Children);
    

    我现在想做的是能够实现同样的事情,只是能够反映类型层次结构。

    x => x.Children { xx => xx.GrandChildren }
    

    提前感谢!

    编辑

    AddProps(x=>x.儿童)。添加Props(xx=>xx.GrandChildren),这将把“Children.GrandChildren”添加到我的“Properties”字符串列表中。

    2 回复  |  直到 17 年前
        1
  •  2
  •   Jeremy Wiebe Tomas Reimers    17 年前

    如果AddProps方法是泛型的,而不是整个Helper类,可能会让事情变得更容易。

    通过这种方式,您可以获得以下代码:

    var helper = new Helper();
    helper.AddProps<Parent>(x => x.Children);
    helper.AddProps<Child>(x => x.GrandChildren);
    

    P.S.知道你为什么要这样做可能会帮助SO社区更好地回答你的问题。

        2
  •  0
  •   ctorx    17 年前

    我最终使用了一种效果很好的替代解决方案。它使用这个新类。..

    public class PartBuilder
    {
        private List<string> Parts;
    
        /// <summary>
        /// Gets a dot delimited string representing the parts
        /// </summary>
        public string Value
        {
            get
            {
                return string.Join(".", this.Parts.ToArray());
            }
        }
    
        /// <summary>
        /// Creates a new PartBuilder
        /// </summary>
        private PartBuilder()
        {
            this.Parts = new List<string>();
        }
    
    
        /// <summary>
        /// Creates a new PartBuilder
        /// </summary>
        public static PartBuilder Create()
        {
            return new PartBuilder();
        }
    
    
        /// <summary>
        /// Gets a property name from an expression
        /// </summary>
        public PartBuilder AddPart<TEntity, TProp>(Expression<Func<TEntity, TProp>> expression)
        {
            PropertyInfo prop = (PropertyInfo)((MemberExpression)(expression.Body)).Member;
            this.Parts.Add(prop.Name);
    
            return this;
        }
    }
    

    既然我有了这个新班级,我就可以做到了。..

    string typeHierarchy = PartBuilder.Create()
                             .AddPart((Parent p) => p.Children)
                             .AddPart((Child pp) => pp.GrandChildren)
                             .Value;
    

    变量“typeHierarchy”现在的值为“Children.GrandChildren”。

    它没有我希望的那么优雅,但它是类型安全且易于使用的。