【问题标题】:Is it possible to get the string of the name of a property in its get and set?是否可以在 get 和 set 中获取属性名称的字符串?
【发布时间】:2017-04-23 11:48:28
【问题描述】:

我想从数据库中存储和检索我的配置。我已经编写了两个方法setConfig(“configName”, value)getConfig(“configName”),并在我的属性中使用它们:

public long MyConfig1
            {
                get
                {
                    return getConfig("MyConfig1");
                }
                set
                {                    
                    setConfig("MyConfig1", value);
                }
            }

但我必须为所有属性编写名称字符串。 是否可以在 set 中获取名称或对当前属性的任何引用并在 C# 中获取? 像这样的:

public long MyConfig1
            {
                get
                {
                    return getConfig(getName(this));
                }
                set
                {                    
                    setConfig(getName(this), value);
                }
            }

【问题讨论】:

    标签: c# .net properties


    【解决方案1】:

    如果您有权访问getConfigsetConfig 方法,请按如下所示修改这些方法。这是最干净的解决方案。

        // using System.Runtime.CompilerServices;
    
        public long MyConfig1
        {
            get
            {
                return getConfig();
            }
        }
    
        private long getConfig([CallerMemberName] string propertyName = null)
        {
        }
    

    但是,如果您无权修改这些方法,请在每个 setter 和 getter 中使用 nameof

        public long MyConfig1
        {
            get { return getConfig(nameof(MyConfig1)); }
        }
    

    【讨论】:

      【解决方案2】:

      你可以写一个方法来使用caller-information attributes:

      // Put this anywhere
      public static string GetCallerName([CallerMemberName] name = null)
          => name;
      

      重要的是,当你调用它时,不要提供一个参数:让编译器来代替:

      public long MyConfig1
      {
          get => GetConfig(Helpers.GetCallerName());
          set => SetConfig(Helpers.GetCallerName(), value);
      }
      

      当然,您也可以在 GetConfigSetConfig 方法中使用相同的属性,然后在调用它们时不提供参数。

      【讨论】:

      • 只是好奇,为什么辅助方法比nameof 更受欢迎?这是为了提取实际逻辑(现在使用CallerMemberName 实现)?
      • 非常感谢!这是我的答案!
      猜你喜欢
      • 2021-08-02
      • 2011-09-30
      • 2014-10-27
      • 1970-01-01
      • 2012-11-16
      • 2014-03-06
      • 2017-08-18
      相关资源
      最近更新 更多