Let's say I have a class that looks like this:
public class CallByAttribute
{
[CodeName("Foo")]
public string MyProperty { get; set; }
[CodeName("Bar")]
public string MyMethod(int someParameter)
{
return myDictionary[someParameter];
}
}
How would I call these two properties or methods, using CodeName instead of the property or method name?
Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element.
Attribute ReflectionReflection is a set of . NET APIs that facilitate retrieving metadata from C# attributes. Reflection is used to retrieve attributes associated with an attribute target. This code calls GetCustomAttributes to list the attribute type names for the Id property.
The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
Method 1:
public static TOutput GetPropertyByCodeName<TOutput>(this object obj, string codeName)
{
var property = obj.GetType()
.GetProperties()
.Where(p => p.IsDefined(typeof(CodeNameAttribute), false))
.Single(p => ((CodeNameAttribute)(p.GetCustomAttributes(typeof(CodeNameAttribute), false).First())).Name == codeName);
return (TOutput)property.GetValue(obj, null);
}
Note: This will throw if no property exists with the specified codeName
or if multiple properties share the same codeName
.
Usage:
CallByAttribute obj= ...
string myProperty = obj.GetPropertyByCodeName<string>("Foo");
Method 2:
If you are on C# 4, you can write your own System.Dynamic.DynamicObject
that can route dynamic calls to the right member.
This will allow for cleaner syntax. For example, you should be able to accomplish something that allows:
CallByAttribute obj= ...
dynamic objectByCodeName = new ObjectByCodeName(obj);
objectByCodeName.Foo = "8";
objectByCodeName.Bar();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With