Get a generic's member names as strings withou

2019-08-16 00:57发布

问题:

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?

回答1:

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);


回答2:

D'oh! The using ClassMembers alias was hiding 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);
    }
}