【问题标题】:How to get the Name of an application setting in C#?如何在 C# 中获取应用程序设置的名称?
【发布时间】:2015-07-10 21:58:21
【问题描述】:

在visual c#的应用程序设置中,我们可以创建一系列具有特定名称、类型、范围和值的设置。我可以通过代码访问该值:

string color= Myproject.Properties.Settings.Default.mycolor;

如何在输出中获得“mycolor”,这是该设置的名称?

【问题讨论】:

  • 您能否说明您是想从设置值(例如“blue”)还是使用设置访问器(“mycolor”属性)检索属性名称?
  • 我想获得“mycolor”而不是价值。我通过使用键“mycolor”创建一个字典来解决它,这样我就可以按值找到键。我有一系列这些设置,所以我发现字典最适合我的应用程序。我对 C# 还很陌生,所以可能还有其他方法可以做到这一点。

标签: c# .net application-settings


【解决方案1】:

如果您想要设置的名称,那么您正在寻找属性名称。在Metaprogramming in .NET 书中,Kevin Hazzard 有一个看起来像这样的例程:

/// <summary>
/// Gets a property name string from a lambda expression to avoid the need
/// to hard-code the property name in tests.
/// </summary>
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}

要调用它,您可以这样做:

string propertyName = GetPropertyName(() => Myproject.Properties.Settings.Default.mycolor);

我在我的一些项目中添加了一个静态反射实用程序,以允许访问此工具和其他工具。

编辑

2015 年 7 月 20 日被设置为 Visual Studio 2015 和 .NET 4.6 的 RTM 日期,这似乎是更新的好时机。

幸运的是,我上面的所有代码都在 C# 6 (.NET 4.6) 中消失了,因为现在有一个新的 nameof 表达式可以很容易地处理这个问题:

string propertyName = nameof(Myproject.Properties.Settings.Default.mycolor);

MSDN blog 上描述了一些新功能。

【讨论】:

  • 只有值,所以字符串颜色,他似乎没有访问权限Settings.Default.mycolor。否则这个问题将毫无意义。
【解决方案2】:

一个小小的扩展方法可以帮助你:

public static string GetSettingName<TObject, TProperty>(this TObject settings, 
    Expression<Func<TObject, TProperty>> member) 
    where TObject : System.Configuration.ApplicationSettingsBase
{
    var expression = (MemberExpression)member.Body;
    return expression.Member.Name;
}

它的用法:

var settingName = Properties.Settings.Default.GetSettingName(s => s.mycolor);

【讨论】:

  • 如果我理解问题 OP 只有颜色,例如“红色”,他想知道相关的设置名称。如果他已经需要使用s.mycolor,那么获取mycolor 将毫无意义。
  • @TimSchmelter:OP 声明 我可以通过代码访问该值(参见示例)并询问 我如何获得“mycolor”,这是名称此设置的。我仍然将其读作“将设置属性名称作为字符串 [使用反射] 给我”。我同意它没用,OP 可以在某处输入“mycolor”。
  • 他可以访问颜色的。但是,也许我误解了它。
  • 从你的回答中我知道你来自哪里。您正在将设置值转换回设置名称,而我将其解释为给定属性访问器,给我属性名称。我已要求 OP 澄清。
【解决方案3】:

这是我对您的要求的理解:

  • 您需要知道对象的设置名称
  • f.e.您想从"Red" 之类的颜色中获取"mycolor"(假设这是默认值)

您可以使用Properties 集合和Enumerable.FirstOrDefault

var colorProperty = Settings.Default.Properties.Cast<System.Configuration.SettingsProperty>()
    .FirstOrDefault(p => color.Equals(p.DefaultValue)); // color f.e "Red"
string nameOfProperty = null;
if (colorProperty != null)
    nameOfProperty = colorProperty.Name;

【讨论】:

    猜你喜欢
    • 2013-04-09
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多