将属性从反射传递到表达式

Jer*_*ose 2 c# reflection asp.net-mvc lambda

我想使用反射遍历我的模型属性,然后将它们传递给一个方法,期望我的属性为en表达式.

例如,给定此模型:

public class UserModel
{
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这个验证器类:

public class UserValidator : ValidatorBase<UserModel>
{
    public UserValidator()
    {
        this.RuleFor(m => m.Username);
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的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
    }
}
Run Code Online (Sandbox Code Playgroud)

问题在于ValidatorBase()构造函数 - 假设我有PropertyInfo我需要的属性,我应该将什么作为expression参数传递给RuleFor方法,这样它就像UserValidator()构造函数中的行一样工作?

或者,我是否应该使用其他东西PropertyInfo来使这个工作?

Jon*_*eet 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);
Run Code Online (Sandbox Code Playgroud)

基本上,这是为属性构建表达式树的问题......来自C#4的动态类型仅用于使其更容易调用,RuleFor而无需通过反射明确地执行此操作.当然,您可以这样做 - 但是您需要获取RuleFor方法,然后MethodInfo.MakeGenericMethod使用属性类型调用,然后调用该方法.