在不知道类型参数的情况下获取通用成员名称作为字符串 [英] Get a generic's member names as strings without knowing the type parameters
问题描述
我正在使用反射来获取一些成员名称作为字符串.我使用的方法是在Google代码上(但我对它所使用的反射/LINQ魔术并不十分了解):
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);
}
}
使用这种方法,可以避免在字符串文字中拼写错误的成员名称,并且可以使用自动重构工具.实现 INotifyPropertyChanged
时很高兴!
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?
推荐答案
最好的方法是忘记 using
指令,而直接使用该类:
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);
这篇关于在不知道类型参数的情况下获取通用成员名称作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!