I'm using a custom attribute to grab a property and then set it's value based on another object's value - I'm using reflection to get the attribute like this:
Class Property:
[MyPropertyName("MyString")]
string myString { get; set; }
Populating code:
public void PopulateMyPropertiesFromObject<T>(MyDataArrays dataArrays, T obj) where T : class, new()
{
Type type = typeof (T);
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
foreach (MyPropertyName propName in PropertyInfo.GetCustomAttributes(true).OfType<MyPropertyName>())
{
//Get the value from the array where MyPropertyName matches array item's name property
object value = GetValue(dataArrays, propName);
//Set the value of propertyInfo for obj to the value of item matched from the array
propertyInfo.SetValue(obj, value, null);
}
}
}
I have a collection of these data arrays and so I'm looping through them instantiating a new object of type T and calling this Populate method to populate the new T for each item in the collection.
What's bugging me is how much I'm looking up the MyPropertyName custom attribute because each call to this method will be passing in the same type for obj. on Average this will happen 25 times and then the object's type will change
Is there any way I can cache the properties with their MyPropertyName attribute?Then I'd just have a list of properties + MyPropertyNames to loop through
Or can I access the attributes in a nicer way than I am?
For context: this is all happening server side of an asp.net website, I've got roughly 200-300 objects, each with around 50 properties using the attribute above for the purposes of the method above
Aucun commentaire:
Enregistrer un commentaire