c# - Accessing same singleton instance and destroying it when it is not required
问题描述
(WPF MVVM)
I have a requirement where I need to access the same instance (following Singleton pattern) and also I want to create/access refreshed instance of above instance.
So what I did is, use singleton pattern(for both Model and ViewModel) at the required time and then destroy it (by setting the instance to value .i.e., giving Singleton.Instance = null) when I need new/refreshed version above Instance as the old object has been already stored in my ObservableCollection.
public sealed class SingletonViewModel
{
private static SingletonViewModel instance=null;
private SingletonViewModel ()
{
}
public static SingletonViewModel Instance
{
get
{
if (instance==null)
{
instance = new SingletonViewModel ();
}
return instance;
}
set
{
instance = value;
}
}
//I have an ObservableCollection of the SingletonViewModel class in other class.
//I am destroying the above instance by setting the Instance value to null.
public void Destroy{
SingletonModel.Instance = null;
SingletonViewModel .Instance = null;
}
public String Header{
get return SingletonModel.Instance.Header;
set { SingletonModel.Instance.Header = value}
}
Though I destroy and try to access the above instance after calling function Destroy, my ObservableCollection is getting updated with the recent value of the above Instance.
解决方案
推荐阅读
- visual-studio-code - 更新后 Visual Studio Code 终端混乱
- python - 如何检测模型属性是否是外键关系?(并检索所有 FK 模型对象)
- node.js - 使用nodejs在firestore云中发送角度表单数据
- laravel - 有没有办法在 voyager 中使用已经创建的数据库表?
- mysql - 阅读进度表中通过select查询计算阅读页数
- vue.js - 要求和导入不适用于 vue.js 中的节点库
- flutter - 在flutter源码中,为什么Dart Generics能写出这样的代码?
- php - 带有 %C2%A0 字符的 htaccess 重定向链接
- python - 即使在定义 lamda_handler 之后,模块 'lambda_function' 上也缺少处理程序 'lambda_handler'
- decimalformat - 无法提供小于小数位数定义的十进制字段