我正在开发一个WPF应用程序。在用户关闭该应用程序之前,我需要一些变量/信息才能销毁。哪种方法最好?带有 Static
变量的 static
类?此外,这种情况下的最佳做法是什么?
答案 0 :(得分:3)
我相信你能做的就是编写一个类,它可以像ASP .net中的会话对象一样为你保存变量。你可以做点什么
public static class ApplicationState
{
private static Dictionary<string, object> _values =
new Dictionary<string, object>();
public static void SetValue(string key, object value)
{
if (_values.ContainsKey(key))
{
_values.Remove(key);
}
_values.Add(key, value);
}
public static T GetValue<T>(string key)
{
if (_values.ContainsKey(key))
{
return (T)_values[key];
}
else
{
return default(T);
}
}
}
保存变量:
ApplicationState.SetValue("MyVariableName", "Value");
读取变量:
MainText.Text = ApplicationState.GetValue<string>("MyVariableName");
这将通过你的应用程序访问所有内容,并将在整个内存中保留。
答案 1 :(得分:2)
在这种情况下,您可以将静态 Class
与静态字段一起使用。他从未被释放,它没有任何析构函数,也没有参与垃圾收集。
如果您希望普通班级保持活着,可以使用方法GC.KeepAlive()
:
SampleClass sample = new SampleClass();
//... Somewhere in the end ...
GC.KeepAlive(sample);
在这里,KeepAlive()
创建了对您的类实例的引用,以便垃圾收集思考,他仍然在您的应用程序中使用。 KeepAlive()
的目的是确保存在对GC
可能过早回收的对象的引用。
引自MSDN
:
此方法引用obj参数,使该对象不具有从例程开始到执行顺序的点的垃圾收集的资格,此处调用此方法。
Code this method at the end, not the beginning, of the range of instructions where obj must be available.
KeepAlive
方法不执行任何操作,除了延长作为参数传入的对象的生命周期外,不会产生任何副作用。
或者,信息可以存储在WPF应用程序设置中。特别是如果信息很重要,不应在系统故障或重启后丢失。
设置位于此处Project -> Properties -> Parameters
。设置新值的示例:
MyProject.Properties.Settings.Default.MyButtonColor = "Red";
保存按如下方式执行:
MyProject.Properties.Settings.Default.Save();
还可以使用带有属性的Binding
,指示Source
中的设置类:
xmlns:properties="clr-namespace:MyProject.Properties"
<TextBlock Text="{Binding Source={x:Static properties:Settings.Default},
Path=MyButtonColor,
Mode=TwoWay}" />
有关在WPF中使用设置的详细信息,请参阅:
答案 2 :(得分:1)
您还可以创建静态类并在xaml中引用它,如下所示:
namespace MyNamespace
{
public static class Globals
{
public static double SomeVariable { get { return 1.0; } }
}
}
然后从xaml访问它,如下所示:
<UserControl Width="{x:Static globals:Globals.SomeVariable}" />
其中globals
定义在xaml的顶部,如下所示:
<Window x:Class="MyNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:globals="clr-namespace:MyNamespace">
</Window>