Skip to main content
 首页 » 编程设计

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

2024年02月13日13myhome

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

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

也许这甚至是不可能的。我最初为 Employment 类设置了两个类: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; 
  } 
} 

请您参考如下方法:

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

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