Lou commented on the last post about using Expression and Func as an expression tool and came up with a much better solution than I had.
I’m going to repost it here for everyone else to see in the RSS reader.
This is the test class of whom we’d like to get the property (and method) names.
public class Thing { public int Height { get; set; } public int Zone(string foo) { return 5; } public void Restore(string bar, string baaz) { } }
This is the updated reflection class that is now static and represents a more fluid/fluent syntax:
public class NameOf<T> { public static string Property<TResult>(Expression<Func<T, TResult>> func) { return (func.Body as MemberExpression).Member.Name; } public static string Method<TResult>(Expression<Func<T, TResult>> func) { return (func.Body as MethodCallExpression).Method.Name; } public static string Method(Expression<Action<T>> func) { return (func.Body as MethodCallExpression).Method.Name; } }
And a simple example:
class Program { static void Main(string[] args) { var name1 = NameOf<Thing>.Property(x => x.Height); var name2 = NameOf<Thing>.Method(x => x.Zone(null)); var name3 = NameOf<Thing>.Method(x => x.Restore(null, null)); } }
A big thanks goes out to Lou!
Leave a Reply
You must be logged in to post a comment.