代码之家  ›  专栏  ›  技术社区  ›  Paul Carlton

将表达式传递给初始值设定项

c#
  •  2
  • Paul Carlton  · 技术社区  · 5 年前

    我想传递一个表示在实例化对象时要使用的变量的表达式。

    而不是:

    class MyObject : IMyInterface { ... }
    
    var list = db.MyObjects.Where(x => !x.IsDeleted).ToList();
    var anotherList = list.Select(x => new AnotherObject() { 
      Id = x.Id,
      Value = x.Value
    });
    

    我想这样做是为了 IMyInterface 可以使用如下定义的表达式转换为另一种类型的列表(另一个对象作为示例):

    var list = db.MyObjects
      .Where(x => !x.IsDeleted)
      .ToAnotherObjectList(x => x.Id, x => x.Value);
    
    ...
    
    public static List<AnotherObject> ToAnotherObjectList<T>(
      this IEnumerable<IMyInterface> list, 
      Expression id, 
      Expression value)
    {
        return list.Select(x => new AnotherObject() { Id = id, Value = value }).ToList();
    }
    

    我不知道该怎么做。我知道我可以使用反射创建对象并通过字符串设置属性,但我不知道如何传递表达式。

    更新

    好吧,我想我得做些反思,但这比我想的要简单。这是我在IRL中的解决方案。

    public static IEnumerable<AnotherObject> ToAnotherObject<T>(this IEnumerable<T> list, Func<T, int> getId, Func<T, string> getValue, Func<T, bool> getSelected = null) where T : IMyInterface
    {
        return list.Select(x => new AnotherObject {
            Display = getValue(x),
            Id = getId(x),
            Selected = getSelected != null && getSelected(x),
        });
    }
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   Julian    5 年前

    你可以用一个 Func<TInput,TReturn> 为了这个。例如:

    public static List<AnotherObject> ToAnotherObjectList<T>(
      this IEnumerable<T> list, 
      Func<T, int> getId,
      Func<T, object> getValue)
    {
        return list.Select(x => new AnotherObject() { Id = getId(x), Value = getValue(x) }).ToList();
    }
    

    呼叫:

    list.ToAnotherObjectList(i => i.Id, i=> i.Value);
    

    在这个例子中,我使用了带有一个参数(t类型)和返回类型int/object的funcs。