我认为最好的解决方案是使用 T4 生成静态常量(例如T4MVC)。
public static class StaticSampleClass
{
public const string MyProperty = "MyProperty";
}
相信我,当您有很多调用时,反射和 linq 表达式正在降低应用程序的性能。
坏事是T4在net core中消失了。:(
您可以使用 C#6.0 中的好东西nameof(SampleClass.MyProperty)
在最坏的情况下,您可以使用以下示例:
using System.Linq.Expressions;
namespace ConsoleApp1
{
public static class Helper
{
public static string GetPropertyName<T>(Expression<Func<T, object>> propertyExpression)
{
var member = propertyExpression.Body as MemberExpression;
if (member != null)
return member.Member.Name;
else
throw new ArgumentNullException("Property name not found.");
}
public static string GetPropertyName<T>(this T obj, Expression<Func<T, object>> propertyExpression)
{
return GetPropertyName(propertyExpression);
}
}
public class SampleClass
{
public string MyProperty { get; set; }
}
class Program
{
static void Main(string[] args)
{
// Property name of type
Console.WriteLine(Helper.GetPropertyName<SampleClass>(x => x.MyProperty));
// Property name of instance
var someObject = new SampleClass();
Console.WriteLine(someObject.GetPropertyName(x => x.MyProperty));
Console.ReadKey();
}
}
}
性能结果(100万次调用):
StaticSampleClass.MyProperty
- 8 毫秒
nameof(SampleClass.MyProperty)
- 8 毫秒
Helper.GetPropertyName<SampleClass>(x => x.MyProperty)
- 2000 毫秒