将类属性传递为通用类型

时间:2015-07-17 02:19:36

标签: c# generics fluentvalidation

我正在尝试为FluentValidation实现一个基类,它将为类快速构建验证器。我的基类函数尝试将类的属性作为通用类型参数来应用规则。但是,正如您在代码中看到的那样,它在语法上(在其他方面)并不正确。

在代码中解释可能要容易得多:

public class BaseValidator<T>  : AbstractValidator<T>
{
    public void ruleForText<U>(string msg)
    {
        RuleFor(obj => obj.U).NotEmpty().WithMessage(msg);
        RuleFor(obj => obj.U).Length(1, 100).WithMessage(msg);
        RuleFor(obj => obj.U).Matches("[A-Z]*").WithMessage(msg);
    }

    public void ruleForEmail<U>(string msg)
    {
        RuleFor(obj => obj.U).NotEmpty().WithMessage(msg);
        RuleFor(obj => obj.U).EmailAddress().WithMessage(msg);
    }
}

public class Member {
    public string Name { get; set; }
    public string Email { get; set; }
}

public class Post{
    public string Title { get; set; }
}

public class MemberValidator :BaseValidator<Member>
{
    public MemberValidator()
    {
        // Not valid syntax to pass name or even Member.Name
        // How can I pass Member.Name as the generic type?
        ruleForText<Name>();
        ruleForEmail<Email>();
    }
}

public class PostValidator :BaseValidator<Post>
{
    public MemberValidator()
    {
        ruleForText<Title>();
    }
}

1 个答案:

答案 0 :(得分:1)

这可能就是你要找的东西。您需要传入一个函数参数为字符串的表达式。

public class BaseValidator<T> : AbstractValidator<T>
{
    public void RuleForText(Expression<Func<T, string>> expression, string msg)
    {
        RuleFor(expression).NotEmpty().WithMessage(msg);
        RuleFor(expression).Length(1, 100).WithMessage(msg);
        RuleFor(expression).Matches("[A-Z]*").WithMessage(msg);
    }

    public void RuleForEmail(Expression<Func<T, string>> expression, string msg)
    {
        RuleFor(expression).NotEmpty().WithMessage(msg);
        RuleFor(expression).EmailAddress().WithMessage(msg);
    }
}

public class MemberValidator : BaseValidator<Member>
{
    public MemberValidator()
    {
        RuleForText(member => member.Name, "My Message");
        RuleForEmail(member => member.Email, "My Message");
    }
}

public class Member
{
    public string Name { get; set; }
    public string Email { get; set; }
}