I am working on a framework that uses some attribute markup. This will be used in the MVC project and will happen approximately every time I look at a specific record in the view (e.g. / Details / 5)
I was wondering if there is a better / more efficient way to do this or a good example of best practices.
Anyway, I have several attributes, for example:
[Foo("someValueHere")] String Name {get;set;} [Bar("SomeOtherValue"] String Address {get;set;}
What is the most efficient way / best practice for finding these attributes / Act on their values?
I am currently doing something like this:
[System.AttributeUsage(AttributeTargets.Property)] class FooAttribute : Attribute { public string Target { get; set; } public FooAttribute(string target) { Target = target; } }
And in my method, where I work on these attributes (simplified example!):
public static void DoSomething(object source) { //is it faster if I make this a generic function and get the tpe from T? Type sourceType = source.GetType(); //get all of the properties marked up with a foo attribute var fooProperties = sourceType .GetProperties() .Where(p => p.GetCustomAttributes(typeof(FooAttribute), true) .Any()) .ToList(); //go through each fooproperty and try to get the value set foreach (var prop in fooProperties) { object value = prop.GetValue(source, null); // do something with the value prop.SetValue(source, my-modified-value, null); } }
Yablargo
source share