2012-12-31 5 views
5

Zasadniczo, jeśli mam kolekcję obiektów, w jaki sposób mogę zastosować atrybut sprawdzania poprawności do każdego elementu w kolekcji (na przykład MaxLengthAttribute)?Jak zastosować atrybuty sprawdzania poprawności do obiektów w kolekcjach?

public class Foo 
{ 
    public ICollection<string> Bars { get; set; } 
} 

Na przykład, w jaki sposób można zapewnić, że Bary zawiera ciągi które pozwalają na ocenę na długości max 256?

Aktualizacja:

rozumiem, jak zastosować atrybut walidacji na jednej nieruchomości, ale pytanie jest pytaniem, jak ją stosować na obiektach w kolekcji.

public class Foo 
{ 
    [StringLength(256)] // This is obvious 
    public string Bar { get; set; } 

    // How do you apply the necessary attribute to each object in the collection! 
    public ICollection<string> Bars { get; set; } 
} 
+0

Entity Framework lub ASP.NET MVC? – abatishchev

+0

@atatishchev: Ani. Po prostu ogólny C#. –

Odpowiedz

-1

Spójrz na funkcjonalność adnotacji danych:

to działa dla Ciebie?

using System.ComponentModel; 
using System.ComponentModel.DataAnnotations; 
public class Foo 
{ 
    [StringLength(256)] 
    public ICollection<string> Bars { get; set; } 
} 
+0

To nie działa, ponieważ StringLengthAttribute w twoim przykładzie jest stosowane do samej kolekcji, a nie do poszczególnych ciągów w kolekcji. –

1

OK znalazłem bardzo ciekawy artykuł wyjaśniający kilka przydatnych informacji na ten temat:

http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/faq-why-does-donotexposegenericlists-recommend-that-i-expose-collection-lt-t-gt-instead-of-list-lt-t-gt-david-kean.aspx

Oto sugerowane kodu, która stałaby członek Batoniki Foo robić, co chcesz.

public class Foo 
{ 
    public ValidatedStringCollection Bars = new ValidatedStringCollection(10); 
} 

public class ValidatedStringCollection : Collection<string> 
{ 

    int _maxStringLength; 

    public ValidatedStringCollection(int MaxStringLength) 
    { 
     _maxStringLength = MaxStringLength; 
    } 

    protected override void InsertItem(int index, string item) 
    { 
     if (item.Length > _maxStringLength) 
     { 
      throw new ArgumentException(String.Format("Length of string \"{0}\" is beyond the maximum of {1}.", item, _maxStringLength)); 
     } 
     base.InsertItem(index, item); 
    } 

} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Foo x = new Foo(); 
     x.Bars.Add("A"); 
     x.Bars.Add("CCCCCDDDDD"); 
     //x.Bars.Add("This string is longer than 10 and will throw an exception if uncommented."); 

     foreach (string item in x.Bars) 
     { 
      Console.WriteLine(item); 
     } 

     Console.ReadKey(); 
    } 
} 

prowadzi link artykuł ma kilka sugestii w tym przesłanianie innych metod na gromadzenie, wdrażanie wydarzeń warunkowo, itd. To powinno obejmować cię nadzieją.

1

Wiem, że to pytanie jest trochę stare, ale może ktoś przychodzi szukać odpowiedzi.

nie jestem świadomy sposób ogólny stosowania atrybutów do elementów kolekcji, ale na konkretnym przykładzie długość łańcucha użyłem następujące:

public class StringEnumerationLengthValidationAttribute : StringLengthAttribute 
{ 
    public StringEnumerationLengthValidationAttribute(int maximumLength) 
     : base(maximumLength) 
    { } 

    public override bool RequiresValidationContext { get { return true; } } 
    public override bool IsValid(object value) 
    { return false; } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var e1 = value as IEnumerable<string>; 
     if (e1 != null) return IsEnumerationValid(e1, validationContext); 
     return ValidationResult.Success; // what if applied to something else than IEnumerable<string> or it is null? 
    } 

    protected ValidationResult IsEnumerationValid(IEnumerable<string> coll, ValidationContext validationContext) 
    { 
     foreach (var item in coll) 
     { 
      // utilize the actual StringLengthAttribute to validate the items 
      if (!base.IsValid(item) || (MinimumLength > 0 && item == null)) 
      { 
       return new ValidationResult(base.FormatErrorMessage(validationContext.DisplayName)); 
      } 
     } 
     return ValidationResult.Success; 
    } 
} 

Zastosuj w następujący sposób, aby wymagać 4-10 znaków każdy przedmiot kolekcji:

[StringEnumerationLengthValidation(10, MinimumLength=4)] 
public ICollection<string> Sample { get; set; }