c# - 实现一个非常基本的 IDisposable

标签 c# .net idisposable

我想实现一个非常简单的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在我的课上?
我的类(class)没有资源可供免费使用。

奖励问题:是否有更好的模式来测量方法的执行时间,而不是像我那样使用 IDisposable

对不起,如果这个问题很愚蠢。我是 .net 的新手
提前致谢。

最佳答案

为了忠实于作用域的概念,您可以将结果注入(inject) IDisposable 的构造函数中。使用接口(interface)来保持灵 active 。我很惊讶没有人提到您的方法中类型安全的损失,我肯定会将泛型类型参数添加到基 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;
    }
}

用法

static MethodResult<int> TestMehodResult()
{
    var timedResult = new MethodResult<int>();

    using (var timer = new MethodTimer(timedResult))
    {
        timedResult.Result = 666;
        Thread.Sleep(1000);
    }

    return timedResult;
}

关于c# - 实现一个非常基本的 IDisposable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361280/

相关文章:

c# - SqlException 未处理 C#

c# - 为什么编译器选择通用方法而不是特定方法?

c# - 如何检测另一个音频是否在后台播放? ( window 电话 7)

c# - 如何使用 C# Windows 窗体创建流畅的动画?

c# - 除非手动删除所有输出文件,否则应用程序不会启动

c# - 在 Visual Studio 2008 中单步执行 C# 时如何找到方法调用方?

c# - 如果 Finalizer 调用 Dispose() ,您可以触发 "Disposing"事件吗?

c# - 我应该有返回 Disposable 实例列表的方法吗?

c#-4.0 - Lazy<T> 与 LazyThreadSafeMode.PublicationOnly 和 IDisposable

c# - 在不允许任意实现时使用接口(interface)隐藏实现细节