C# 如何获取特定属性的PropertyInfo?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/491429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the PropertyInfo of a specific property?
提问by tenpn
I want to get the PropertyInfo for a specific property. I could use:
我想获取特定属性的 PropertyInfo。我可以使用:
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
But there must be a way to do something similar to
但是必须有一种方法可以做类似的事情
typeof(MyProperty) as PropertyInfo
Is there? Or am I stuck doing a type-unsafe string comparison?
在那儿?还是我一直在做类型不安全的字符串比较?
Cheers.
干杯。
采纳答案by Kevin Kalitowski
You can use the new nameof()
operator that is part of C# 6 and available in Visual Studio 2015. More info here.
您可以使用作为nameof()
C# 6 一部分且在 Visual Studio 2015 中可用的 new运算符。更多信息请点击此处。
For your example you would use:
对于您的示例,您将使用:
PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));
The compiler will convert nameof(MyObject.MyProperty)
to the string "MyProperty" but you gain the benefit of being able to refactor the property name without having to remember to change the string because Visual Studio, ReSharper, and the like know how to refactor nameof()
values.
编译器将转换nameof(MyObject.MyProperty)
为字符串“MyProperty”,但您可以获得能够重构属性名称而不必记住更改字符串的好处,因为 Visual Studio、ReSharper 等知道如何重构nameof()
值。
回答by Vojislav Stojkovic
You can do this:
你可以这样做:
typeof(MyObject).GetProperty("MyProperty")
However, since C# doesn't have a "symbol" type, there's nothing that will help you avoid using string. Why do you call this type-unsafe, by the way?
但是,由于 C# 没有“符号”类型,因此没有什么可以帮助您避免使用字符串。顺便说一句,你为什么称这种类型不安全?
回答by Darin Dimitrov
Reflection is used for runtime type evaluation. So your string constants cannot be verified at compile time.
反射用于运行时类型评估。所以你的字符串常量不能在编译时验证。
回答by Marc Gravell
There is a .NET 3.5 way with lambdas/Expression
that doesn't use strings...
有一种 .NET 3.5 方式使用 lambdas/Expression
不使用字符串......
using System;
using System.Linq.Expressions;
using System.Reflection;
class Foo
{
public string Bar { get; set; }
}
static class Program
{
static void Main()
{
PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);
}
}
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}