在不知道类型参数的情况下将泛型成员名称作为字符串获取 [英] Get a generic's member names as strings without knowing the type parameters
问题描述
我使用反射来将一些成员名称作为字符串。我正在使用我发现的方法在谷歌代码上(但我没有很好地理解它使用的反射/ 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))
抛出新的InvalidOperationException(表达式必须是成员访问权限);
返回node.Member.Name;
$ b 这在静态构造函数中很有用。我只是像这样使用它:
使用ClassMembers = MembersOf< MyClass>;
class MyClass
{
public int MyProperty {get;组; }
static MyClass
{
string lMyPropertyName = ClassMembers.GetName(x => x.MyProperty);
$ b $ p
$ b 使用这种方法避免拼写错误的字符串中的成员名并可以使用自动重构工具。在执行 INotifyPropertyChanged
!
时很高兴,但现在我有一个泛型类,我想在同样的方式,和我学会了,您不能使用非绑定类型作为泛型类型参数:
使用ClassMembers = MembersOf< MyGeneric<>取代;
class MyGeneric< T> {}
解决这个问题的一个好方法是什么?
$ b $最好的方法是使用
指令来忘记并直接使用该类: string propName = MembersOf< MyGeneric< T>> .GetName(x => x.SomeProp);
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?
解决方案 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屋!