[英]Passing property from reflection into expression
我想使用反射遍歷模型屬性,然后將它們傳遞到將我的屬性視為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
,我應該在RuleFor
方法中將其作為expression
參數傳遞給它,以便它就像UserValidator()
構造函數中的行一樣工作?
或者,我應該使用PropertyInfo
之外的其他工具來使它正常工作嗎?
我懷疑您想要:
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
,然后調用該方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.