是否有可能使用的DataAnnotations与接口?有可能、接口、DataAnnotations

2023-09-03 00:06:45 作者:花开念伊人

我想用的DataAnnotations验证类,实现了一些接口,所以我加入验证属性界面,像这样的:

I want to use DataAnnotations to validate classes that implements some interfaces, and so I'm adding validation attributes to the interface, like this:

public interface IUser
{
    [Required]
    string Name { get; set; }

    [Display(Name = "Email Address")]
    [Required]
    string Email { get; set; }
}

当我尝试使用它不能正常工作 Validator.TryValidateObject

It doesn't work when I try to use Validator.TryValidateObject.

有没有什么办法让,而不必编写自定义这个 TryValidateObject 的方法?

Is there any way to make this instead of having to write a custom TryValidateObject method?

推荐答案

如果您使用接口的基类来代替,该属性将正常工作。

If you use a base class instead of an interface, the attributes will work fine.