1

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

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

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

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

4 回答 4

3

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

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

于 2013-09-27T15:15:38.513 回答
1

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

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

于 2013-09-27T15:28:35.097 回答
0

我认为您正在搜索 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));
于 2013-09-27T15:19:18.270 回答
0

由于我尝试做的事情似乎不太可能,因此我根据@user1578874 的建议找到了一种不同的方法。我向就业添加了一个 IsRequired 属性,并使用 MVC Foolproof Validation 将这些属性标记为 [RequiredIf("IsRequired")]。似乎是最干净的解决方案。

于 2013-09-27T18:32:44.623 回答