标识方法的开始和结束

Identity Start and End of a method

我正在为一个方法创建跟踪并希望它与自定义属性一起使用。我将用 TraceMethod.

装饰每个方法

例如:

[TraceMethod()]
public void SomeMethod()
{
}

public class TraceMethod : Attribute
{
 public void StartTrace(){}

 public void EndTrace(){}
}

所以在这里,

如何在SomeMethod开始执行前调用StartTrace()SomeMethod执行结束后调用EndTrace()?可能吗?

您正在尝试做的是 Aspect-Oriented Programming, which is something that is currently not supported out-of-the-box in the .NET world. You will have to use a third-party component; there are some out there,付费和开源。

也许创建一个自定义 class 来标记函数的范围?在函数的开头创建 class 的实例,当函数终止时 class 超出范围并调用析构函数。

构造函数和析构函数标记函数的开始和结束。

编辑: 正如所评论的那样,不能保证在对象超出范围后立即调用析构函数。更好的是使用 using() 块:

public void SomeMethod()
{
    using (TraceMethod trace = new TraceMethod())
    {
    }
}

public class TraceMethod : IDisposable
{
    public TraceMethod() { StartTrace(); }  // Constructor
    public void Dispose() { EndTrace(); }  // Gets called when leaving the using() block

    private void StartTrace() { ... }
    private void EndTrace() { ... }
}

您可以修改方法体:

public void SomeMethod()
{
    var trace = new Trace();
    try
    {
        ... rest of method
    }
    finally
    {
        trace.EndTrace();
    }
}

public class TraceMethod : Attribute
{
    public TraceMethod() => StartTrace();

    public void StartTrace() { ... }
    public void EndTrace() { ... }
}