Is it possible to create global settings that are visible to all classes in the project? [Like modules in VB]
I am creating a project with many classes. I need to have a kind of settings class AKA module in VB that is accessible from all other classes. I want to know a 开发者_StackOverflow社区method to achieve that without creating a separate settings object and passing it to each other class constructor.
Thanks
Use a static class with static fields
public static class Settings
{
public static string a = "a";
public static string b = "b";
public static bool c = true;
}
and in your other classes
if(Settings.c) ...
You can use the ConfigurationManager
class. This has the bonus of working with the standard .NET config files.
As far as I know, My.Settings
is a wrapper around this class.
The easiest way to accomplish this is to create a public static class. Under the covers, that's all VB does anyway.
Here is something I just did. This uses YAXLib (http://yaxlib.codeplex.com/) but you could use any serializer. I don't know how good the example is though.
public class FrameworkSettings
{
public static int ListenPort { get; set; }
public static int NumberOfOutgoingLines { get; set; }
public static void Load(FrameSettings settings)
{
ListenPort = settings.ListenPort;
NumberOfOutgoingLines = settings.NumberOfOutgoingLines;
}
}
public class FrameSettings
{
[YAXErrorIfMissed(YAXExceptionTypes.Warning, DefaultValue = 5060)]
public int ListenPort { get; set; }
[YAXErrorIfMissed(YAXExceptionTypes.Warning, DefaultValue = 5)]
public int NumberOfOutgoingLines { get; set; }
public void Save()
{
ListenPort = FrameworkSettings.ListenPort;
NumberOfOutgoingLines = FrameworkSettings.NumberOfOutgoingLines;
}
}
public class SettingsManager
{
YAXSerializer _mSerializer;
FrameSettings _mFrameSettings;
public SettingsManager()
{
_mFrameSettings = new FrameSettings();
if (!Directory.Exists("data"))
{
Directory.CreateDirectory("data");
}
}
public void LoadSettings()
{
_mSerializer = new YAXSerializer(typeof(FrameSettings),
YAXExceptionHandlingPolicies.ThrowErrorsOnly,
YAXExceptionTypes.Warning);
_mFrameSettings = (FrameSettings)_mSerializer.DeserializeFromFile("data\\settings.xml");
FrameworkSettings.Load(_mFrameSettings);
}
public void SaveSettings()
{
_mFrameSettings.Save();
_mSerializer.SerializeToFile(_mFrameSettings, "data\\settings.xml");
}
static class is one way. But config files were made to hold the settings and are more appropriate and easy to use. they are accessed using ConfigurationManager class.
精彩评论