在编译之前将代码插入到 C# 方法中

Inserting code into C# methods right before compilation

我有几个方法是从 WinForms 应用程序的入口点调用的。这些方法依次调用其他方法,有时还会相互调用。

在每个方法的入口处,我都插入了如下代码:

public static bool IsDebug
{
    #if (DEBUG)
        return (true);
    #else
        return (false);
    #endif
}

public void SomeMethod ()
{
    if (IsDebug) { Logger.WriteMethodTrace(MethodBase.GetCurrentMethod().Name); }
}

这种方法有两个问题:

.
REFLECTION:新的 C# nameof(parameter) 关键字非常适用于参数名称,但我还没有找到类似的方法名称结构。我考虑过创建某种静态字典来保存 TypeMethodInfo 详细信息,但似乎没有办法在运行时提取方法名称而无需反射以用作字典中的键。

手工编写:即使有避免反射的解决方案,每个方法都需要手工修改,既繁琐又容易出错。我想知道是否有一种方法可以在编译之前及时插入一行代码。不确定是 VS 扩展还是 Roslyn 会在这里提供帮助。理想情况下,如果可以自动插入,则应该在不实际修改源代码的情况下进行插入。

请注意,分析堆栈跟踪不是一种选择。我一直沿着那条路走下去,它很慢而且不愉快。

任何 pointers/suggestions 将不胜感激。

C# 5.0 为您提供了一项不错的功能。我认为这对您来说很有用:

[Conditional("DEBUG")]
public void LogMethodNameInDebug(
    [CallerMemberName] string memberName = "",
    [CallerFilePath] string sourceFilePath = "", 
    [CallerLineNumber] int sourceLineNumber = 0)
{
    Logger.WriteMethodTrace(memberName);
)


public void SomeMethod()
{
    LogMethodNameInDebug(); // don't fillin the methodnames yourself, the compiler will do.
}

[Conditional("DEBUG")] 将在将其编译为 Release 构建时排除该方法。查找更多信息:MSDN - ConditionalAttribute

并且 [CallerMemberName] 将在编译时填充 (它填充调用方的参数,因此不使用反射或堆栈分析) 。有关 [CallerMemberName] 的更多信息,请点击此处:MSDN - CallerMemberNameAttribute