Custom Attributes, named parameters and reflection
Hi.
I am trying to find the most fasted way of doing this when it comes to reflection.
Say I have a custom attribute which allows multiples on a property.
I then want to get a list of properties which contains this custom attribute. Thats ok, I get a collection of these attributes for that property.
I then, for each of the attributes found, want to get the value for a specific named argument.
how can I do this and in the most efficient way? Reflection does have a hit but im sure with some decent algorithms/different calls it can save those few ms's
thanks
Re: Custom Attributes, named parameters and reflection
I'm not sure that there is any way other than something like this:
Code:
private Dictionary<string, string[]> GetAttributeValues(object source)
{
var attributeValuesByPropertyName = new Dictionary<string, string[]>();
var properties = source.GetType().GetProperties();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(typeof(MultipleValueAttribute), false);
var attributesLength = attributes.Length;
if (attributesLength > 0)
{
var values = new string[attributesLength];
for (int i = 0; i < attributesLength; i++)
{
values[i] = ((MultipleValueAttribute)attributes[i]).Value;
}
attributeValuesByPropertyName.Add(property.Name, values);
}
}
return attributeValuesByPropertyName;
}
You could shorten that code with a bit of LINQ but that would make it slower to execute, if only by a little. Sample usage:
Code:
var obj = new Test();
var attributeValues = this.GetAttributeValues(obj);
foreach (var propertyName in attributeValues.Keys)
{
MessageBox.Show(string.Join("\r\n", attributeValues[propertyName]), propertyName);
}
That was based on the following attribute:
Code:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class MultipleValueAttribute : Attribute
{
public string Value { get; set; }
}
Re: Custom Attributes, named parameters and reflection
thanks. I just managed to figure it out before you posted :) thats pretty much what I have.
Re: Custom Attributes, named parameters and reflection
I'm sure that it's not quite as glamorous as mine. ;)