我需要关于单例模式的确认。
我有一个单例类,我将它用作 dll。我编写了一个引用此 dll 的程序,并调用了我的单例类。我写了第二个程序,我也这样做。
如果我告诉你,即使我有两个程序,它们都调用我的单例类的单个实例,我对吗?
我试图增加一个静态变量 instancenumber ,每次我通过构造函数时都会增加它,两个程序都告诉我 instancenumber 是 1。所以应该没问题,但我需要你的建议来确定。
谢谢你。此致
单例类:
namespace SingletonClassLib
{
public class SingletonClass
{
public static int InstanceNumber = 0;
private static string myName;
#region //Singleton initialisation
private SingletonClass() { createInstance(); }
private void createInstance()
{
InstanceNumber++;
myName = myName + InstanceNumber.ToString();
}
public static SingletonClass _I { get { return NTCSession._i; } }
private class NTCSession
{
static NTCSession() { }
internal static readonly SingletonClass _i = new SingletonClass();
}
private static …Run Code Online (Sandbox Code Playgroud) 假设我创建了一个对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CreateObjOnobj
{
class Program
{
static void Main(string[] args)
{
testcreate myobjecttotest;
myobjecttotest = new testcreate();
myobjecttotest.num = 20;
myobjecttotest.bill = true;
myobjecttotest = new testcreate();
Console.WriteLine(myobjecttotest.bill.ToString());
Console.ReadKey();
}
}
class testcreate
{
public int num = 0;
public bool bill = false;
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码是否会自动删除对象并创建一个新对象而不会丢失内存?
谢谢