【问题标题】:How can I retrieve the instance of an attribute's associated object?如何检索属性关联对象的实例?
【发布时间】:2010-04-07 19:38:12
【问题描述】:

我正在编写一个PropertiesMustMatch 验证属性,它可以将字符串属性名称作为参数。我希望它在该对象上按名称查找相应的属性并进行基本的相等比较。 通过反射访问它的最佳方式是什么?

另外,我检查了企业库中的验证应用程序块,并认为它的 PropertyComparisonValidator 过于密集,无法满足我们的需要。

更新:为了进一步澄清(提供一些上下文),目标只是强制字段匹配的验证(例如,密码验证)。如果可能,我们希望它与继承自 ValidationAttribute 类的属性级属性数据注释一起使用。

更新:万一有人好奇,我最终通过调整代码解决了实际的业务问题,作为question的答案提供了@

【问题讨论】:

    标签: c# validation reflection attributes


    【解决方案1】:

    你不能,基本上。检查对象是否存在属性的代码还必须负责告诉任何代码它正在查看的类型/对象。您无法从 within 属性中获取任何其他元数据。

    【讨论】:

    • 是否有最好的解决方法?可悲的是,它看起来并不像这样简单:[MustMatchValidator(this, "FieldToMatch")]
    【解决方案2】:

    你不能那样做。另见this question。尝试更改逻辑以使用对象,检查其属性,反之亦然。您还可以提供有关您的任务的更多信息,而不仅仅是这个狭隘的问题。

    【讨论】:

      【解决方案3】:

      你可以这样。

      //target class
      public class SomeClass{
      
        [CustomRequired(ErrorMessage = "{0} is required", ProperytName = "DisplayName")]
        public string Link { get; set; }
      
        public string DisplayName { get; set; }
      }
      //custom attribute
      public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable
      {
        public string ProperytName { get; set; }
      
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
          var propertyValue = "Value";
          var parentMetaData = ModelMetadataProviders.Current
               .GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType());
          var property = parentMetaData.FirstOrDefault(p => p.PropertyName == ProperytName);
          if (property != null)
              propertyValue = property.Model.ToString();
      
          yield return new ModelClientValidationRule
          {
              ErrorMessage = string.Format(ErrorMessage, propertyValue),
              ValidationType = "required"
          };
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-29
        • 2013-01-21
        相关资源
        最近更新 更多