如何将C#属性名称作为带reflection的字符串?
可能重复:
c# – 如何获得变量的名称,因为它在声明中是物理输入的?
我正在寻找一种方法来获取属性名称作为字符串,所以我可以有一个“强类型”魔术字符串。 我需要做的是像MyClass.SomeProperty.GetName()这样会返回“SomeProperty”。 这可能在C#中吗?
您可以使用表达式轻松实现此目的。 请参阅此博客以获取示例 。
这使得您可以通过lambda创建表达式,并提取名称。 例如,可以重新实现INotifyPropertyChanged以执行以下操作:
public int MyProperty { get { return myProperty; } set { myProperty = value; RaisePropertyChanged( () => MyProperty ); } }
为了映射您的等价物,使用引用的“reflection”类,您可以执行以下操作:
string propertyName = Reflect.GetProperty(() => SomeProperty).Name;
Viola – 没有魔术字符串的属性名称。
这种方法比使用Expression
更快
public static string GetName(this T item) where T : class { if (item == null) return string.Empty; return typeof(T).GetProperties()[0].Name; }
现在你可以打电话给它:
new { MyClass.SomeProperty }.GetName();
如果需要更高的性能,可以缓存值。 看到这个重复的问题如何获得变量的名称,因为它在声明中是物理输入的?
您可以使用reflection获取对象的属性列表。
MyClass o; PropertyInfo[] properties = o.GetType().GetProperties( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
每个Property都有一个Name属性,可以获得“SomeProperty”