如果我在C#中引用了一个属性,如何引用包含对象

时间:2015-03-03 13:14:41

标签: c# model-view-controller customvalidator

我正在实现自定义验证(MVC DataAnnotations),我有这样的类结构

class Parent()
{

    public Child ChildObject1{get;set;}
    public Child ChildObject2{get;set;}

}

class Child()
{

    public GrandChild GrandChildObject1{get;set;}
    public GrandChild GrandChildObject2{get;set;}
       etc.
}

class GrandChild()
{
    public Flags FlagsThatAffectValidationOnSomeProperties {get;set;}

    [CustomValidation]
    private string _myProperty;
}

我想编写自定义验证代码,我需要访问FlagsThatAffectValidationOnSomeProperties对象。我将参考文献传递给了父母' “验证关联”中的实例' IsValid覆盖的对象

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        this.ErrorMessage = string.Empty;
        if (!validationContext.Items.ContainsKey(ContextItemKeys.Parent))
            return ValidationResult.Success;


        Parent parent = (Parent)validationContext.Items[ContextItemKeys.Parent];

...

但是如何获得对GrandchildObject1.FlagsThatAffectValidationOnSomeProperties的引用,以便我可以正确验证传入的_myProperty?

1 个答案:

答案 0 :(得分:1)

您可以使用validationContext.ObjectInstance获取要验证的对象的当前实例,并使用反射来访问属性值。如果需要,您还可以包含其他检查以确保实例确实是Grand Child的实例。

protected virtual object GetPropertyValue(ValidationContext validationContext, string propertyName)
{
   var properties = validationContext.ObjectInstance.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

   var property = properties.FirstOrDefault(x => x.Name == propertyName);
   if (property == null)
      return null;

   var propertyValue = property.GetValue(validationContext.ObjectInstance, null);
   return propertyValue;
}

var propertyValue = GetPropertyValue(validationContext, "FlagsThatAffectValidationOnSomeProperties");

//如果不为null,则将值转换为枚举,并使用值