2009-08-14 50 views
3

我想知道是否有人知道如果我的模型类实现的接口,而不是直接在具体模型类上定义我的system.componentmodel.dataannotations属性,如果xVal将按预期工作。如果在接口上定义属性,xVal是否会工作?

public interface IFoo 
{ 
    [Required] [StringLength(30)] 
    string Name { get; set; } 
} 

,然后在我的模型类不会有任何验证属性...

public class FooFoo : IFoo 
{ 
    public string Name { get; set; } 
} 

如果我尝试验证与XVAL一个FooFoo,它将使用其界面attribs?

回答

4

目前xVal.RuleProviders.DataAnnotationsRuleProvider只查看模型类本身定义的属性。您可以在方法GetRulesFromProperty在规则提供基类PropertyAttributeRuleProviderBase看到这一点:

protected virtual IEnumerable<Rule> GetRulesFromProperty(
    PropertyDescriptor propertyDescriptor) 
{ 
    return from att in propertyDescriptor.Attributes.OfType<TAttribute>() 
      from validationRule in MakeValidationRulesFromAttribute(att) 
      where validationRule != null 
      select validationRule; 
} 

propertyDescriptor参数代表的属性在模型类及其Attributes财产仅代表直接对物业本身定义的属性。

但是,您当然可以扩展DataAnnotationsRuleProvider并覆盖相应的方法以使其按照您所需执行:从已实现的接口中提取验证属性。然后你可以XVAL注册您的规则提供商:

ActiveRuleProviders.Providers.Clear(); 
ActiveRuleProviders.Providers.Add(new MyDataAnnotationsRuleProvider()); 
ActiveRuleProviders.Providers.Add(new CustomRulesProvider()); 

要实现的接口得到属性的属性,你应该扩展DataAnnotationsRuleProvider并覆盖GetRulesFromTypeCore。它得到一个System.Type类型的参数,其方法为GetInterfaces

+0

感谢您的详细解答!我猜接下来的问题是:是否有一种简单的方法来迭代类实现的接口?您需要这样做才能获取接口上每个属性的PropertyDescriptors。 – NathanD 2009-08-14 20:59:26

+0

我添加了一些关于如何获得一个类型的实现接口的信息。 – 2009-08-15 20:12:00

+0

看起来很直接,谢谢一堆! – NathanD 2009-08-16 03:52:38

相关问题