2010-04-30 4 views
2

Prenez cette classe par exemple:C# travailler avec les membres Décorés

public class Applicant : UniClass<Applicant> 
{ 
    [Key] 
    public int Id { get; set; } 

    [Field("X.838.APP.SSN")] 
    public string SSN { get; set; } 

    [Field("APP.SORT.LAST.NAME")] 
    public string FirstName { get; set; } 

    [Field("APP.SORT.FIRST.NAME")] 
    public string LastName { get; set; } 

    [Field("X.838.APP.MOST.RECENT.APPL")] 
    public int MostRecentApplicationId { get; set; } 
} 

Comment puis-je obtenir toutes les propriétés qui sont décorées avec l'attribut de champ, obtenir leurs types, puis attribuez-lui une valeur pour les ?

Répondre

2

Vous devez utiliser la réflexion:

var props = 
    from prop in typeof(Applicant).GetProperties() 
    select new { 
     Property = prop, 
     Attrs = prop.GetCustomAttributes(typeof(FieldAttribute), false).Cast<FieldAttribute>() 
    } into propAndAttr 
    where propAndAttr.Attrs.Any() 
    select propAndAttr; 

Vous pouvez ensuite parcourir cette requête pour définir les valeurs:

foreach (var prop in props) { 
    var propType = prop.Property.PropertyType; 
    var valueToSet = GetAValueToSet(); // here's where you do whatever you need to do to determine the value that gets set 
    prop.Property.SetValue(applicantInstance, valueToSet, null); 
} 
4

Tout est fait avec la réflexion. Une fois que vous avez un objet Type, vous pouvez alors obtenir son PropertyInfo avec myType.GetProperties(), à partir de là, vous pouvez obtenir les attributs de chaque propriété avec GetCustomAttributes(), et de là si vous trouvez votre attribut, vous avez un gagnant, et vous pouvez ensuite procéder à travaillez avec lui comme vous s'il vous plaît.

Vous avez déjà l'objet PropertyInfo, de sorte que vous pouvez lui assigner avec PropertyInfo.SetValue(object target, object value, object[] index)

1

Vous juste besoin d'invoquer les méthodes de réflexion appropriées - essayez ceci:

<MyApplicationInstance>.GetType().GetProperties().Where(x => x.GetCustomAttributes().Where(y => (y as FieldAttribute) != null).Count() > 0);