在 .NET 中处理单例对象
我有两个类 ClassA 和 ClassB 都具有对单例对象 ClassHelper 的引用。我的问题是使用 ClassA 和 ClassB 完成后我应该如何处理单例对象
编辑:
public ClassA
{
CHelper obj;
public ClassA()
{
obj = obj.GetInstance("Initialise");
obj.CallFuncA();
}
}
On the same lines
public ClassB
{
CHelper obj;
public ClassB()
{
obj = obj.GetInstance("Initialise");
obj.CallFuncB();
}
}
where
CHelper
{
private static sm_CHelper;
public static GetInstance(string strInitialise)
{
if(sm_CHelper == null)
{
sm_CHelper = new CHelper(strInitialise);
}
}
private CHelper(string strInitialise)
{
//do something here
}
public CallFuncA()
{
// do something here
}
public CallFuncB()
{
// do something here
}
}
问候 学习者
I have two classes ClassA and ClassB both having a reference to a singleton object ClassHelper. My question is how should i dispose the singleton object once im done using both the ClassA and ClassB
Edit:
public ClassA
{
CHelper obj;
public ClassA()
{
obj = obj.GetInstance("Initialise");
obj.CallFuncA();
}
}
On the same lines
public ClassB
{
CHelper obj;
public ClassB()
{
obj = obj.GetInstance("Initialise");
obj.CallFuncB();
}
}
where
CHelper
{
private static sm_CHelper;
public static GetInstance(string strInitialise)
{
if(sm_CHelper == null)
{
sm_CHelper = new CHelper(strInitialise);
}
}
private CHelper(string strInitialise)
{
//do something here
}
public CallFuncA()
{
// do something here
}
public CallFuncB()
{
// do something here
}
}
Regards
Learner
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您正在谈论模式 singleton,那么您不应该处置它......如果您没有提到 singleton 模式,那么您可以尝试使用解构函数来运行您的处置逻辑。
if you are talking about the pattern singelton then you should not dispose it.... if your not referring to the singelton pattern then you could try to use the deconstructor to run your dispose logic.
该单例应该在应用程序期间保持活动状态。因此,在处理 A 类和 B 类产品时,不应将其丢弃。
That singleton should remain alive for the duration of the application. So you shouldn't dispose of it when disposing of those ClassA and ClassB's.
我从未见过这样的例子。我可能会这样做:
这样,在 ClassA 和 ClassB 检出资源后,静态引用将停止保留它。在 ClassA 和 ClassB 失去对资源的引用后,终结器将在下一轮垃圾收集中被调用。
I've never seen an example like this. I'd probably do something like:
this way, after both ClassA and ClassB checkout the Resource, the static reference stops keeping it around. After ClassA and ClassB lose their reference to the Resource, the finalizer gets called the next round of garbage collection.