如何获得在C#中的应用程序设置的名称? [英] How to get the Name of an application setting in C#?

查看:296
本文介绍了如何获得在C#中的应用程序设置的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Visual C#中的应用程序设置,我们可以创建一系列设置特定名称,类型,范围和价值。我得到code访问值:

In application setting of visual c#, we can create a series of settings with specific Name, Type, Scope and Value. I have access to the value by the code:

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

我怎样才能获得mycolor,这是该设置的名称,在输出?

How can I get "mycolor", which is the name of this setting, in the output?

推荐答案

如果你想设置的名称,那么你希望得到的属性名。在这本书中元编程在.NET中,凯文·哈扎德有一个程序,看起来是这样的:

If you want the name of the setting, then you are looking to get the property name. In the book Metaprogramming in .NET, Kevin Hazzard has a routine that looks something like this:

/// <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;
}

要调用它,你会做这样的:

To call it you would do this:

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

我添加了一个静态的反射工具来我的一些项目,以便获得这个和其他工具。

I've added a static reflection utility to some of my projects to allow for access to this and other tools.

修改

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

With July 20, 2015 being set as the RTM date for Visual Studio 2015 and .NET 4.6, this seems like a good time for an update.

令人高兴的是,我所有的上述code消失在C#6(.NET 4.6)因为有一个新的nameof EX pression是完成这个功能很容易,现在:

Happily, all of my above code goes away in C# 6 (.NET 4.6) since there is a new nameof expression that takes care of this very easily now:

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

一些新功能上的 MSDN博客

这篇关于如何获得在C#中的应用程序设置的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆