Get common member names as strings without knowing type parameters

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?

0
source share
2 answers

The best way would be to forget the using directive and just use the class directly:

 string propName = MembersOf<MyGeneric<T>>.GetName(x => x.SomeProp); 
+1
source

D'ah! The using ClassMembers hid the obvious. I just need to use MembersOf<MyGeneric<T>> directly in my class!

 class MyGeneric<T> { public int MyProperty { get; set; } static MyClass<T> { string lMyPropertyName = MembersOf<MyGeneric<T>>.GetName(x => x.MyProperty); } } 
0
source

All Articles