我想要获取特定属性的PropertyInfo。我可以使用:
foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
if ( p.Name == "MyProperty") { return p }
}
但必须有一种方法来做一些类似的事情
typeof(MyProperty) as PropertyInfo
在那里吗?或者我被困在做一个类型不安全的字符串比较?
干杯。
发布于 2015-12-18 00:37:52
你可以使用新的nameof()
运算符,它是C# 6的一部分,在Visual Studio2015中可用。更多信息here。
在您的示例中,您将使用:
PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));
编译器会将nameof(MyObject.MyProperty)
转换为字符串"MyProperty“,但您可以获得重构属性名而不必记住更改字符串的好处,因为Visual Studio、ReSharper等知道如何重构nameof()
值。
发布于 2009-01-29 12:50:47
有一种不使用字符串的lambdas/Expression
的.NET 3.5方式...
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();
}
}
}
发布于 2009-01-29 12:40:20
您可以这样做:
typeof(MyObject).GetProperty("MyProperty")
但是,由于C#没有"symbol“类型,因此没有什么可以帮助您避免使用字符串。顺便说一句,为什么你称这种类型是不安全的?
https://stackoverflow.com/questions/491429
复制相似问题