C # works with decorated members

Take this class for example:

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; }
}

      

How do I get all the properties that are decorated with a field attribute, get their types and then assign a value to them?

+2


a source to share


3 answers


You will need to use Reflection:

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;

      



Then you can iterate through this query to set the values:

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

      

+2


a source


All this is done with reflection. When you have an object Type

, you can get its PropertyInfo with myType.GetProperties()

, from there you can get every attribute of the property with GetCustomAttributes()

, and from there, if you find your attribute, you have a winner, and then you can start working with it as you would whatever.



You already have a PropertyInfo object, so you can assign to it PropertyInfo.SetValue(object target, object value, object[] index)

+4


a source


You just need to call the appropriate reflection methods - try this:

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

      

+1


a source







All Articles