use*_*425 3 c# oop class stopwatch
嗨我正在尝试创建一个我可以在我的项目中使用的全局类,我打算使用它作为我的默认模板,我是新手所以请耐心等待;)
Stopwatch Masterstopwatch = new Stopwatch();
#if DEBUG
private static void ApplicationLogStart()
{
StartTime = DateTime.Now;
Masterstopwatch.Start();
String eventName = "Program Loaded";
String errorDetails = "Program has started Succesfully";
DataLogEntry(eventName, errorDetails);
}
private static void ApplicationLogclosing()
{
String eventName = "Program is closing";
String errorDetails = "Program has closed Succesfully";
DataLogEntry(eventName, errorDetails);
StopTime = DateTime.Now;
Masterstopwatch.Stop();
Benchmark(StartTime,StopTime,Masterstopwatch.Elapsed);
}
#endif
Run Code Online (Sandbox Code Playgroud)
我怀疑我的设计存在缺陷,因为我想要秒表Masterstopwatch =新的秒表(); 要在全球范围内宣布而不使用某种方法,我怀疑这是不可能的,但我需要问谢谢
听起来你需要Singleton模式.
如果您按如下方式在秒表周围声明包装,则可以在应用程序的任何位置使用它并访问秒表的相同实例.
// Declare singleton wrapper of a stopwatch, which instantiates stopwatch
// on construction
public class StopwatchProxy
{
private Stopwatch _stopwatch;
private static readonly StopwatchProxy _stopwatchProxy = new StopwatchProxy();
private StopwatchProxy()
{
_stopwatch = new Stopwatch();
}
public Stopwatch Stopwatch { get { return _stopwatch; } }
public static StopwatchProxy Instance
{
get { return _stopwatchProxy; }
}
}
// Use singleton
class Foo
{
void Foo()
{
// Stopwatch instance here
StopwatchProxy.Instance.Stopwatch.Start();
}
}
class Bar
{
void Bar()
{
// Is the same instance as here
StopwatchProxy.Instance.Stopwatch.Stop();
}
}
Run Code Online (Sandbox Code Playgroud)