4

嗨,我正在尝试制作一个可以在我的项目中使用的全局类,我打算将其用作我的默认模板,我是新手,所以请耐心等待;)

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

我怀疑我的设计存在根本缺陷,因为我想要秒表 Masterstopwatch = new Stopwatch(); 要在不使用方法的情况下全局声明,我怀疑这是不可能的,但我需要问谢谢

4

1 回答 1

7

听起来您需要Singleton Pattern

如果您如下声明秒表的包装器,您可以在应用程序的任何位置使用它并访问相同的秒表实例。

// 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();
    }
}
于 2012-05-19T22:47:23.023 回答