【发布时间】:2017-03-02 10:03:45
【问题描述】:
像我试图做的那样使用单例惰性比我想象的要困难。 但我认为我已经完成了 50%。我的问题是关于下一个代码,为什么我需要通过 Instanciation _I 到达“int 函数”而不是通过 _I 到达结构? 单例权利是实施还是我不明白? 谢谢
代码
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Example_Singleton.Singleton.Data.Act_Number + "\n");
Console.WriteLine(Example_Singleton.Singleton.Time.TLength_Form.Time50ms.ToString()+"\n");
Example_Singleton.Singleton.Time._IT.waitTimer(3000);
Console.WriteLine("done");
Console.ReadKey();
}
}
class Example_Singleton
{
public sealed class Singleton
{
private Singleton()
{
}//ctor singleton
public static Singleton _I { get { return Nested.instance; } }//instance called for singleton
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() { }//ctor nested
internal static readonly Singleton instance = new Singleton();
}
public struct Data
{//base structure for data station
public static Int16 Act_Number = 352;
}
public sealed class Time/* Class Time for PSX*/
{
private Time()
{
}//ctor
public static Time _IT { get { return thisTime.instance; } }
private class thisTime
{
static thisTime() { }//ctor
internal static readonly Time instance = new Time();
}
internal void waitTimer(Int32 TimeLength) //Wait timer
{
System.Threading.Thread.Sleep(TimeLength);
}
internal struct User_Time
{
public const int RefreshData = 100;
public const int WaitSynchro = 10;
}
internal struct TLength_System //time length definitions for system time
{
public const double Time10ms = 10;
public const double Time50ms = 50;
}
internal struct TLength_Form //time length definitions for Form time
{
public const int Time10ms = 10;
public const int Time50ms = 50;
}
}
}
【问题讨论】:
-
你到底想用这个单例模式做什么?看来你建立了一些非常复杂的东西,你可能不需要。
-
我只想拥有一堆使用过的嵌套类的一个实例,很多 Formclass 都在使用这些嵌套类。像 Time 一样,我们不需要很多 tomer 实例。或者,我会添加一个服务器类单例,其中只有一个实例方法 Read 和 write 可以被 intanciated,所以我确信一次只有一个调用者访问服务器......这就是重点。
标签: c# function class nested singleton