2016-07-06 74 views
1

我有使用C#6以下通用類:通用方法用的Ti和Ti + 1

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(路徑)。

有沒有簡化我的代碼的方法?我將至少需要4個像這樣的方法,直到路徑7.

+2

簡答題:不可以擴展答案:[here](http://stackoverflow.com/questions/15417174/using-the-params-keyword-for-generic-parameters-in-c-sharp) – lokusking

回答

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); 

    ... 
} 

你仍然需要每個要支持「通用的元數」的另一種方法,但至少實現很簡單。

當然,如果你想成爲能夠指定多個路徑,但每個路徑必須是同一類型的,這很簡單 - 因爲你可以使用params類型的參數。但是參數必須是一個特定的Expression<TDelegate>類型,如果你想能夠使用lambda表達式作爲參數,並且它看起來像你想能夠改變所涉及的類型。