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;
How can I get "mycolor", which is the name of this setting, in the output?
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.
EDIT
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.
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);
Some of the new features are described on the MSDN blog.
A little extension method will help you out here:
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;
}
And it's usage:
var settingName = Properties.Settings.Default.GetSettingName(s => s.mycolor);
Here is my understanding of your requirement:
- You need to know the setting-name from an object
- f.e. you want to get
"mycolor"
from a color like"Red"
(presuming that this is the default-value)
You can use the Properties
collection and 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;
来源:https://stackoverflow.com/questions/25898872/how-to-get-the-name-of-an-application-setting-in-c