I am using a Custom Attribute to define how a class’s members are mapped to properties for posting as a form post (Payment Gateway). I have the custom attribute working just fine, and am able to get the attribute by ‘name’, but would like to get the attribute by the member itself.
For example:
getFieldName('name');
vs
getFieldName(obj.Name);
The plan is to write a method to serialize the class with members into a postable string.
Here’s the test code I have at this point, where ret is a string and PropertyMapping is the custom attribute:
foreach (MemberInfo i in (typeof(CustomClass)).GetMember('Name')) { foreach (object at in i.GetCustomAttributes(true)) { PropertyMapping map = at as PropertyMapping; if (map != null) { ret += map.FieldName; } } }
Thanks in advance!
You can’t really do this, unless you’re using C# 3.0 in which case you’ll need to rely on LINQ (ehm, expression trees).
What you do is that you create a dummy method for a lambda expression which lets the compiler generate the expression tree (compiler does the type checking). Then you dig into that tree to get the member. Like so:
Given the following class:
You can get the meta data like this:
With a reference to that field you can then dig up any attribute the usual way. i.e. reflection.
Now you can dig up an attribute on any field by something which is in large checked by the compiler. It also works with refactoring, if you rename ‘a’ Visual Studio will catch that.
There’s not a single literal string in that code there.