[英]Why multiple instances of static class being created?
Suppose I have 3 DLL's. 假设我有3个DLL。 DLL #1 and #2 depend on DLL #3. DLL#1和#2依赖于DLL#3。 DLL #3 contains a static class such as: DLL#3包含一个静态类,例如:
public class ImportTimer
{
public static bool EnableProcessorTimerLogging { get; set; }
public static bool EnableTimerLogging { get; set; }
public static DateTime SourceDataDetectionTimestamp { get; set; }
public static DateTime LastEndProcessTimestamp { get; set; }
static ImportTimer()
{
EnableProcessorTimerLogging = false;
EnableTimerLogging = false;
SourceDataDetectionTimestamp = DateTime.Now;
LastEndProcessTimestamp = DateTime.Now;
}
...
}
All of the methods are static. 所有方法都是静态的。 DLL #1 and #2 do not know about each other (no dependencies on the other). DLL#1和#2彼此不了解(彼此之间没有依赖性)。 When I invoke any method from DLL #1 and then invoke the same method on DLL #2, I see a new copy of the static object get created in DLL #2 (it is not using the same copy as DLL #1). 当我从DLL#1调用任何方法,然后在DLL#2上调用相同的方法时,我看到在DLL#2中创建了静态对象的新副本(它没有使用与DLL#1相同的副本)。 So now I have 2 copies of ImportTimer when I only wanted one for both DLL's to share. 所以现在当我只想共享两个DLL时,我有2个ImportTimer副本。 How can I get the 2 DLL's to share the same static instance? 如何获得2个DLL来共享相同的静态实例?
Your class is not static. 您的课程不是静态的。 The static
constructor lets you initialize static members, it's called automatically before your class is instantiated . static
构造函数使您可以初始化静态成员, 该静态成员会在实例化类之前自动调用 。
You can mark you class as static
as well, by doing static class ImportTimer
. 您也可以通过执行static class ImportTimer
将类标记为static
。
a static class remains in memory for the lifetime of the application domain in which your program resides. 在程序所在的应用程序域的生存期内,静态类将保留在内存中。
However, this means you cannot have anything but static members in your class. 但是,这意味着您的班上除静态成员外别无其他。
Alternatively, you can use a pattern to ensure that there is only 1 instance created, for that you can use the Singleton Pattern . 另外,您可以使用模式来确保仅创建1个实例,为此您可以使用Singleton Pattern 。
In your ImportTimer
, you want to set your constructor to private
. 在ImportTimer
,您想将构造函数设置为private
。 Why? 为什么? Because that way no one else but the class can create the instance. 因为那样的话,除了类之外没有其他人可以创建实例。
Add a static property to get an instance of your class: 添加静态属性以获取您的类的实例:
private static ImportTimer instance;
public static ImportTimer Instance
{
if(instance == null) instance = new ImportTimer();
return instance;
}
Then in DLL #1 and #2, you can use ImportTimer.Instance
to get the shared, static instance. 然后在DLL#1和#2中,可以使用ImportTimer.Instance
获取共享的静态实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.