如何在C#中获取应用程序设置的名称?

时间:2014-09-17 19:33:13

标签: c# .net application-settings

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

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

如何在输出中获取" mycolor",这是此设置的名称?

3 个答案:

答案 0 :(得分:3)

如果您想要设置的名称,那么您希望获取属性名称。在书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)中消失了,因为有一个新的表达式,现在很容易处理这个问题:

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

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

答案 1 :(得分: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);

答案 2 :(得分:1)

以下是我对您的要求的理解:

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

您可以使用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;