Tutorial :C# working with decorated members



Question:

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 would I go about getting all of the properties that are decorated with the field attribute, get their types, and then assign a value to them?


Solution:1

You'll 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;  

You can then iterate through this query to set the values:

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


Solution:2

This is all done with reflection. Once you have a Type object, you can then get its PropertyInfo with myType.GetProperties(), from there, you can get each property's attributes with GetCustomAttributes(), and from there if you find your attribute, you've got a winner, and then you can proceed to work with it as you please.

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


Solution:3

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

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »