Ti和Ti + 1的通用方法

时间:2016-07-06 09:13:43

标签: c#

我使用C#6有以下泛型类:

public class IncludeMapper<T1> {

  private readonly Dictionary<String, List<LambdaExpression>> _properties = new Dictionary<String, List<LambdaExpression>>();

  public IncludeMapper<T1> Add<T2, T3>(String property, Expression<Func<T1, T2>> path1, Expression<Func<T2, T3>> path2) {

    if (!_properties.ContainsKey(property))
      _properties.Add(property, new List<LambdaExpression> { path1, path2 });

    return this;

  }

  public IncludeMapper<T1> Add<T2, T3, T4>(String property, Expression<Func<T1, T2>> path1, Expression<Func<T2, T3>> path2, Expression<Func<T3, T4>> path3) {

    if (!_properties.ContainsKey(property))
      _properties.Add(property, new List<LambdaExpression> { path1, path2, path3 });

    return this;

  }

}

Add方法有一些表达式(路径),它们只占一个Ti和Ti + 1.

有没有办法简化我的代码?在路径7之前,我至少还需要4个这样的方法。

1 个答案:

答案 0 :(得分:4)

  

有没有办法简化我的代码?

好吧,你可以将它简化为

public class IncludeMapper<T1> {

    private readonly Dictionary<String, List<LambdaExpression>> _properties =
        new Dictionary<String, List<LambdaExpression>>();

    private IncludeMapper<T1> AddImpl(
        string property,
        params LambdaExpression[] expressions)
    {
        if (!_properties.ContainsKey(property))
        {
            _properties.Add(property, paths.ToList());
        } 
        return this;
    }

    public IncludeMapper<T1> Add<T2, T3>(
        String property,
        Expression<Func<T1, T2>> path1,
        Expression<Func<T2, T3>> path2) =>
        AddImpl(path1, path2);

    public IncludeMapper<T1> Add<T2, T3, T4>(
        String property,
        Expression<Func<T1, T2>> path1,
        Expression<Func<T2, T3>> path2,
        Expression<Func<T3, T4>> path3) =>
        AddImpl(path1, path2, path3);

    ...
}

每个&#34;通用arity&#34;你还需要另一种方法。你想要支持,但至少实现是微不足道的。

当然,如果您希望能够指定多个路径,但每个路径必须属于同一类型,那很容易 - 因为那时您可以将params一起使用单个类型的参数。但是,如果您希望能够将lambda表达式用作参数,那么参数必须是特定的Expression<TDelegate>类型,并且看起来您希望能够改变所涉及的类型。