我想获取特定属性的PropertyInfo.我可以用:
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
Run Code Online (Sandbox Code Playgroud)
但必须有办法做类似的事情
typeof(MyProperty) as PropertyInfo
Run Code Online (Sandbox Code Playgroud)
在那儿?还是我坚持做一个类型不安全的字符串比较?
干杯.
Mar*_*ell 130
有一个.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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Kev*_*ski 55
您可以使用nameof()
属于C#6 的新运算符,并在Visual Studio 2015中提供.此处有更多信息.
对于您的示例,您将使用:
PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));
Run Code Online (Sandbox Code Playgroud)
编译器将转换nameof(MyObject.MyProperty)
为字符串"MyProperty",但您可以获得能够重构属性名称而不必记住更改字符串的好处,因为Visual Studio,ReSharper等知道如何重构nameof()
值.
Voj*_*vic 12
你可以这样做:
typeof(MyObject).GetProperty("MyProperty")
Run Code Online (Sandbox Code Playgroud)
但是,由于C#没有"符号"类型,因此没有什么可以帮助您避免使用字符串.顺便说一句,为什么你称这种类型不安全?