如何使用表达式和/或反射获取常量名称

本文关键字:获取 常量 反射 何使用 表达式 | 更新日期: 2023-09-27 18:33:57

如何使用表达式和/或反射获取常量名称?

我已经写了下面,但"我"总是空的?

 public static class Test1
    {
        public const string CampaignManager = "This_CAMPAIGN_MANAGER";
    }
 public static class ReflectionHelper
    {
        // <summary>
        // Get the name of a static or instance property from a property access lambda.
        // </summary>
        // <typeparam name="T">Type of the property</typeparam>
        // <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
        // <returns>The name of the property</returns>
        public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
        {
            var me = propertyLambda.Body as MemberExpression;
            if (me == null)
            {
                throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
            }
            return me.Member.Name;
        }
    }
var campaignManager = ReflectionHelper.GetPropertyName(() => Test1.CampaignManager);

如何使用表达式和/或反射获取常量名称

您不能将常量字段与反射帮助程序一起使用,因为 lambda 表达式的主体是ConstantExpression而不是MemberExpression。取代

 public const string CampaignManager = "This_CAMPAIGN_MANAGER";

 public static string CampaignManager = "This_CAMPAIGN_MANAGER";

似乎您无法获得常量名称,因为

ReflectionHelper.GetPropertyName(() => Test1.CampaignManager);

变成

ReflectionHelper.GetPropertyName(() => "This_CAMPAIGN_MANAGER");

通过编译器