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

时间:2023-01-12 17:01:09

I have a class (Application) that has multiple properties of the type of another custom class (Employment). I would like to validate that Employment class conditionally based on whether the property of the Application class is marked with [Required].

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

From what I've found, I think I should be utilizing the IValidatableObject interface for Employment. The problem is that I'm not sure how to use reflection (or something else maybe) to check if this instance of the class is annotated with the [Required] attribute to determine whether to validate it or not.

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

Maybe this isn't even possible. I initially set up two classes for the Employment class: Employment and EmploymentRequired. Only the latter had the validation attributes on its properties. It works, but I'd like to just have one class to use if possible.

也许这甚至不可能。我最初为就业班设立了两个班级:就业和就业需求。只有后者在其属性上具有验证属性。它有效,但我想尽可能使用一个类。

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 个解决方案

#1


3  

You should be able to check for the required attribute using Attribute.IsDefined.

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

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

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

#2


1  

Seems like you can't do this, because using reflection you can't get parent object/class that references your current instance and all the more so reference property information.

好像你不能这样做,因为使用反射你不能获得引用你当前实例的父对象/类以及所有引用属性信息。

EDIT: Maybe you can make Employment type Generic with required and non required validation modes?

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

#3


0  

I think you are searching for the Attribute.IsDefined method. You would have to first obtain the reference to the field itself, and then validate the presence of the attribute. Like the following (adapted from the example at MSDN):

我认为您正在搜索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));

#4


0  

Since what I'm trying to do doesn't seem to be possible exactly, I found a different way to do it, based on the suggestion of @user1578874. I added an IsRequired property to Employment and used MVC Foolproof Validation to mark those properties as [RequiredIf("IsRequired")]. Seems to be the cleanest solution.

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

#1


3  

You should be able to check for the required attribute using Attribute.IsDefined.

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

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

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

#2


1  

Seems like you can't do this, because using reflection you can't get parent object/class that references your current instance and all the more so reference property information.

好像你不能这样做,因为使用反射你不能获得引用你当前实例的父对象/类以及所有引用属性信息。

EDIT: Maybe you can make Employment type Generic with required and non required validation modes?

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

#3


0  

I think you are searching for the Attribute.IsDefined method. You would have to first obtain the reference to the field itself, and then validate the presence of the attribute. Like the following (adapted from the example at MSDN):

我认为您正在搜索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));

#4


0  

Since what I'm trying to do doesn't seem to be possible exactly, I found a different way to do it, based on the suggestion of @user1578874. I added an IsRequired property to Employment and used MVC Foolproof Validation to mark those properties as [RequiredIf("IsRequired")]. Seems to be the cleanest solution.

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