将 Class 属性 作为通用类型传递

Pass Class Property as Generic Type

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

用代码解释可能更容易:

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

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

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