【发布时间】:2021-12-29 21:08:49
【问题描述】:
我想在c#中实现以下c++代码, 我希望它只在调试中工作
public class Test
{
~Test()
{
//code
}
}
#if DEBUG
#define TEST_DEBUG Test test;
#else
#define TEST_DEBUG
#endif
void Func()
{
TEST_DEBUG
//code
}
我尝试使用 c# 中的 using 语句来实现它。
我有一个实现 IDisposable 的 Test 类。 GetTest函数在release中直接返回null,c#编译器并未对其进行优化。
有什么可以实现的吗?
这里是示例代码:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Test GetTest()
{
#if DEBUG
return new Test();
#else
return null;
#endif
}
private static void Main(string[] args)
{
{
using var test = GetTest();
Console.WriteLine("test");
}
}
public class Test : IDisposable
{
public void Dispose()
{
}
}
ildasm 中的代码(发行版)
.maxstack 1
.locals init ([0] class ConsoleApp2.Program/Test test)
IL_0000: call class ConsoleApp2.Program/Test ConsoleApp2.Program::GetTest()
IL_0005: stloc.0
.try
{
IL_0006: ldstr "test"
IL_000b: call void [mscorlib]System.Console::WriteLine(string)
IL_0010: leave.s IL_001c
} // end .try
finally
{
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001b
IL_0015: ldloc.0
IL_0016: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_001b: endfinally
} // end handler
IL_001c: ret
} // end of method Program::Main
补充: 我尝试使用Action,但它比使用语句更慢。
public static Test(Action action)
{
#if DEBUG
using var test = new Test();
#endif
action();
}
public static void Main(string[] args)
{
Test(() => Console.WriteLine("test"));
}
【问题讨论】:
-
但是为什么呢?你想用你的
Test实例实现什么? -
我想做一些额外的操作,比如记录函数的运行时间