【发布时间】:2017-03-04 21:28:12
【问题描述】:
我有一个Settings 类将设置参数存储为Properties。这个类有其默认的Property 变量,我想随时将它们设置为默认值。我在视频课程中看到过这种用法,但我记不清他是如何做到的。请帮忙。
Settings.cs
class Settings
{
static Settings()
{
SaveDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Type = ImageFormat.Png;
}
public static string SaveDir
{
get;
set;
}
public static ImageFormat Type
{
get;
set;
}
}
Form.cs
Debug.WriteLine(Settings.SaveDir);
Settings.SaveDir = "path_to_another_directory";
Debug.WriteLine(Settings.SaveDir);
//In this line I expect that variables set their default
//but it stays the same
new Settings();
Debug.WriteLine(Settings.SaveDir);
此代码没有按我的预期工作。如何调用 new Settings() 重新分配这些值?
【问题讨论】:
-
好吧,因为他们是
static。static项目的要点是,尽管有实例数量,但只有一个副本。 -
您不能调用静态构造函数,但是您可以添加一个名为 Reset() 的方法并重新分配初始值
-
好的,我已经想出将
static访问修饰符更改为public给出了调用new Settings()的解决方案。我记错了,视频课中使用了static,所以我强迫自己使用static。对不起这个愚蠢的问题。解决方案比我想象的要简单。Reset也是另一种方法。 -
当心,因为现在您的类不再是静态的,更改属性只会影响该实例。
-
虽然这确实有效,但这不是最佳解决方案,因为每次您想重置时都会创建一个
Settings对象。这就是为什么最好使用静态Reset()方法的原因。
标签: c# constructor static