I'm using reflection to get some member names as strings. I'm using a method I found on Google Code (but I don't have a strong grasp of the reflection/LINQ magic it uses):
public static class MembersOf<T> {
public static string GetName<R>(Expression<Func<T,R>> expr) {
var node = expr.Body as MemberExpression;
if (object.ReferenceEquals(null, node))
throw new InvalidOperationException("Expression must be of member access");
return node.Member.Name;
}
}
This works great in static constructors. I just use it like this:
using ClassMembers = MembersOf<MyClass>;
class MyClass
{
public int MyProperty { get; set; }
static MyClass
{
string lMyPropertyName = ClassMembers.GetName(x => x.MyProperty);
}
}
With this approach you avoid misspelling member names in string literals and can use automatic refactoring tools. It's nice to have when implementing INotifyPropertyChanged
!
But now I have a generic class that I want to use in the same manner, and I've learned that you can't use unbound types as generic type parameters:
using ClassMembers = MembersOf<MyGeneric<>>;
class MyGeneric<T> { }
What would be a good way to work around this problem?