2012-09-06 26 views
2

我想循環使用反射的模型屬性,然後將它們傳遞到期望我的屬性爲en表達式的方法中。將屬性從反射傳遞到表達式

例如,假設這種模式:

public class UserModel 
{ 
    public string Name { get; set; } 
} 

這驗證器類:

public class UserValidator : ValidatorBase<UserModel> 
{ 
    public UserValidator() 
    { 
     this.RuleFor(m => m.Username); 
    } 
} 

而且我ValidatorBase類:

public class ValidatorBase<T> 
{ 
    public ValidatorBase() 
    { 
     foreach (PropertyInfo property in 
        this.GetType().BaseType 
         .GetGenericArguments()[0] 
         .GetProperties(BindingFlags.Public | BindingFlags.Insance)) 
     { 
      this.RuleFor(m => property); //This line is incorrect!! 
     } 
    } 

    public void RuleFor<TProperty>(Expression<Func<T, TProperty>> expression) 
    { 
     //Do some stuff here 
    } 
} 

的問題是與ValidatorBase()構造 - - 鑑於我有我需要的房產PropertyInfo,wha t我應該傳入RuleFor方法中的expression參數,這樣它就像UserValidator()構造函數中的行一樣工作?

或者,除了PropertyInfo之外,我還應該使用其他方法來使其工作嗎?

回答

5

我懷疑你想:

ParameterExpression parameter = Expression.Parameter(typeof(T), "p"); 
Expression propertyAccess = Expression.Property(parameter, property); 
// Make it easier to call RuleFor without knowing TProperty 
dynamic lambda = Expression.Lambda(propertyAccess, parameter); 
RuleFor(lambda); 

基本上它是建立一個表達式樹的屬性從C#4 ...動態類型的問題只是用來使其更容易調用RuleFor沒有明確地這樣做通過反思。你當然可以用來做 - 但是你需要去取RuleFor方法,然後用屬性類型調用MethodInfo.MakeGenericMethod,然後調用該方法。

+0

+1非常好的技巧與'動態':) – dasblinkenlight

+0

完美。謝謝。 :) –