2009-08-14 14 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

相關問題