3 回答

TA貢獻1827條經驗 獲得超8個贊
您可以使用新的nameof()操作符是在Visual Studio的C#6部分,2015年提供更多信息這里。
對于您的示例,您將使用:
PropertyInfo result = typeof(MyObject).GetProperty(nameof(MyObject.MyProperty));
編譯器將轉換nameof(MyObject.MyProperty)為字符串“ MyProperty”,但由于Visual Studio,ReSharper等知道如何重構nameof()值,因此您無需重構就可以重構屬性名,從而獲得了好處。

TA貢獻1786條經驗 獲得超11個贊
帶有lambdas /的.NET 3.5方式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();
}
}
}

TA貢獻1810條經驗 獲得超5個贊
你可以這樣做:
typeof(MyObject).GetProperty("MyProperty")
但是,由于C#沒有“符號”類型,因此沒有什么可以幫助您避免使用字符串。順便說一下,為什么將這種類型稱為不安全類型?
添加回答
舉報