实现一个非常基本的IDisposable

问题描述 投票:1回答:1

我想实现一个非常简单的IDisposable。整个想法是衡量我的方法的执行时间,它们全部返回一个MethodResult。例如

public class MethodResult : IDisposable
{
    private Stopwatch _StopWatch;
    public MethodResult()
    {
        _StopWatch = new Stopwatch();
        _StopWatch.Start();
    }
    public object Result { get; set; }
    public TimeSpan ExecutionTime { get; set; }

    public void Dispose()
    {
        _StopWatch.Stop();
        ExecutionTime = _StopWatch.Elapsed;
    }
}

用法:

static MethodResult TestMehodResult()
{
    using (var result = new MethodResult())
    {
        result.Result = 666;
        Thread.Sleep(1000);
        return result;
    }
}

我的问题非常简单:在这种情况下,仅实现Dispose()方法就足够了吗,还是应该在类中实现整个Dispose pattern?我的课堂上没有免费的资源。

奖金问题:是否有更好的模式来衡量方法的执行时间,而不是像我一样使用Dispose

抱歉,这个问题很愚蠢。我真的是.net新手预先感谢。

c# .net idisposable
1个回答
0
投票

为了忠于范围的概念,您可以将结果注入IDisposable的构造函数中。使用界面保持灵活性。令我惊讶的是,没有人提到您的方法中类型安全性的损失,我肯定会在基IDisposable类中添加泛型类型参数(正如您在注释中提到的那样)。

MethodResult

用法

public interface ITimed
{
    TimeSpan ExecutionTime { get; set; }
}

public class MethodResult<T> : ITimed
{
    public T Result { get; set; }
    public TimeSpan ExecutionTime { get; set; }
}

public class MethodTimer : IDisposable
{
    private readonly Stopwatch _StopWatch;
    private ITimed _result;

    public MethodTimer(ITimed result)
    {
        _result = result;
        _StopWatch = new Stopwatch();
        _StopWatch.Start();
    }

    public void Dispose()
    {
        _StopWatch.Stop();
        _result.ExecutionTime = _StopWatch.Elapsed;
        _result = null;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.