检查类的实例是否用属性注释

本文关键字:属性 注释 是否 实例 检查 | 更新日期: 2023-09-27 18:33:14

我有一个类(应用程序),它具有另一个自定义类(就业)类型的多个属性。我想根据应用程序类的属性是否标记为 [必需] 有条件地验证该 Employment 类。

根据我的发现,我认为我应该使用IValidatableObject接口进行就业。问题是我不确定如何使用反射(或其他东西)来检查类的这个实例是否用 [Required] 属性注释以确定是否验证它。

也许这甚至是不可能的。我最初为就业类设置了两个类:就业和就业要求。只有后者在其属性上具有验证属性。它有效,但如果可能的话,我想只使用一个类。

public class Application
{
  [Required]
  public Employment Employer1 { get; set; }
  public Employment Employer2 { get; set; }
}
public class Employment : IValidatableObject
{
  [Required]
  public string EmployerName { get; set; }
  [Required]
  public string JobTitle { get; set; }
  public string Phone { get; set; }
  public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
  {
    var results = new List<ValidationResult>();
    var t = this.GetType();
    //var pi = t.GetProperty("Id");
    //var isRequired = Attribute.IsDefined(pi, typeof(RequiredAttribute));
    //how can I get the attributes of this property in Application class?
    if (isRequired)
    {
        Validator.TryValidateProperty(this.EmployerName,
            new ValidationContext(this, null, null) { MemberName = "EmployerName" }, results);
        Validator.TryValidateProperty(this.JobTitle,
            new ValidationContext(this, null, null) { MemberName = "JobTitle" }, results);
    }
    return results;
  }
}

检查类的实例是否用属性注释

您应该能够使用 Attribute.IsDefined 检查所需的属性。

http://msdn.microsoft.com/en-us/library/system.attribute.isdefined.aspx

似乎你不能这样做,因为使用反射你无法获取引用当前实例的父对象/类,更无法引用属性信息。

编辑:也许您可以使用必需和非必需的验证模式使就业类型通用?

我认为您正在搜索Attribute.IsDefined方法。您必须首先获取对字段本身的引用,然后验证属性是否存在。如下所示(改编自 MSDN 中的示例):

// Get the class type (you can also get it directly from an instance)
Type clsType = typeof(Application);
// Get the FieldInfo object
FieldInfo fInfo = clsType.GetField("Employer1");
// See if the Required attribute is defined for the field 
bool isRequired = Attribute.IsDefined(fInfo , typeof(RequiredAttribute));

由于我正在尝试做的事情似乎不可能完全实现,因此我根据@user1578874的建议找到了另一种方法。我向"就业"中添加了一个 IsRequired 属性,并使用 MVC 万无一失验证将这些属性标记为 [RequiredIf("IsRequired")]。似乎是最干净的解决方案。