I have code like:
var mySetting = ConfigurationManager.AppSettings["m开发者_如何学编程ySetting"];
Is there a way to create properties that encapsulate each setting so I don't have to use string keys like "mySetting"? I know you can do that by creating a "custom configuration section", but I don't want to make another section... I want to use the existing <appSettings> section.
Another option would be create a separate interface that you could use to retrieve the application settings
public interface IFooSettings
{
int MySettings{get;}
}
public class ApplicationSettings : IFooSettings
{
public string MySettings{get; private set;}
ApplicationSettings()
{
MySettings = ConfigurationManager.AppSettings["mySetting"];
}
}
The power of this would be if for some reason you wanted to start saving your configuration in the database the only thing you would need to do is derive a class from IFooSettings to use a database
public class SqlApplicationSettings : IFooSettings
{
SqlApplicationSettings()
{
//Do Something to populate the settings
}
public string MySettings{get; private set;}
}
Granted this might be a bit of overkill for your application but it would offer a lot of flexability since you would not be tied to the ConfigurationManager or some other source.
Yes - use the Visual Studio provided "Settings" classes - use "Add New Item" and then pick "Settings".
This gives you a class with strongly-typed properties (string, int etc.) and all.
This will add the entries it needs in app.config in a custom config section - but it's really all provided for you already, so why reinvent the wheel?
Marc
Check out Configuration Section Designer which will allow you to do this graphically in Visual Studio.
http://www.codeproject.com/KB/cs/genuilder.aspx will allow you to do this in ASP.NET projects
精彩评论