在不知道类型参数的情况下,以字符串形式获取泛型's成员名

本文关键字:泛型 获取 成员 类型参数 不知道 情况下 字符串 | 更新日期: 2023-09-27 18:08:02

我使用反射来获得一些成员名作为字符串。我正在使用我在Google Code上找到的方法(但我对它使用的反射/LINQ魔法没有很强的掌握):

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

这在静态构造函数中非常有效。我只是这样使用它:

using ClassMembers = MembersOf<MyClass>;
class MyClass
{
    public int MyProperty { get; set; }
    static MyClass
    {
        string lMyPropertyName = ClassMembers.GetName(x => x.MyProperty);
    }
}

使用这种方法可以避免在字符串字面量中拼写错误的成员名,并且可以使用自动重构工具。

在实现INotifyPropertyChanged时很好。

但是现在我有一个泛型类,我想以同样的方式使用它,我已经知道你不能使用未绑定类型作为泛型类型参数:

using ClassMembers = MembersOf<MyGeneric<>>;
class MyGeneric<T> { }

解决这个问题的好方法是什么?

在不知道类型参数的情况下,以字符串形式获取泛型's成员名

最好的方法是忘记using指令,直接使用类:

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

D'oh!using ClassMembers别名掩盖了显而易见的事实。我只需要在课堂上直接使用MembersOf<MyGeneric<T>> !

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