Reputation: 13145
Using reflection I can do ToString
on a property. But is there a way to supply a formatting while doing this?
public static object GetCustomValue(object src, string propName)
{
return src.GetType().GetMethod(propName).GetValue(src, null);
}
Calling the function like this works fine
GetCustomValue(obj, "ToString")
But I would like to call it with
GetCustomValue(obj, "ToString(\"MMM\")")
Is it possible to add formatting to the ToString when calling the GetMethod
in my function?
Upvotes: 3
Views: 545
Reputation: 1626
If your ToString accepts paramters (the default one doesn't) add an extra optional parameter:
public static Object GetCustomValue (object Target, string MethodName, String Format = null)
{
// Gets the ToString method that accepts a string as the parameter and invoke it.
return Target.GetType ()
.GetMethod (MethodName, new [] {typeof (String)})
.Invoke (Target, new Object[] {Format});
}
This way you can call it:
GetCustomValue (obj, "ToString", "MMM");
Upvotes: 3
Reputation: 1185
Yes, you can use out of the method name .ToString(format);
GetPropertyValue(obj, "ToString").ToString(format);
Upvotes: 1