I use reflection to get member names as strings. I use the method I found in Google Code (but I don't have a strong understanding of the reflection magic / LINQ that 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 spelling names in string literals and you can use automatic refactoring tools. When implementing INotifyPropertyChanged !
But now I have a general class that I want to use in the same way, and I found out that you cannot use unrelated types as a general type of parameters:
using ClassMembers = MembersOf<MyGeneric<>>; class MyGeneric<T> { }
What would be a good way around this problem?
M. Dudley
source share