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

标签 c# .net generics constants

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

我写了下面的但“我”总是空的?

 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);

最佳答案

您不能将 const 字段与反射助手一起使用,因为 lambda 表达式的主体是 ConstantExpression 而不是 MemberExpression。 替换

 public const string CampaignManager = "This_CAMPAIGN_MANAGER";

 public static string CampaignManager = "This_CAMPAIGN_MANAGER";

关于c# - 如何使用表达式和/或反射获取常量名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19161281/

相关文章:

c# - C#2 中泛型的限制

C# 从泛型值到字符串的转换问题

c# - 为什么我的计数器不增加?

c# - 将 double 限制为小数点后 3 位

c# - 在同步调用的异步代码中捕获异常

c# - MSBuild 条件编译

c# - 使用正则表达式不允许 10 位数字后有小数点

c# - MySQL 从流中读取失败

c# - 获取字符串集合中当前删除索引

java - 泛型类的类型特定构造函数