【问题标题】:How to make the using statement take effect only in debug?如何让using语句只在debug时生效?
【发布时间】: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 语句来实现它。

我有一个实现 IDisposableTest 类。 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 实例实现什么?
  • 我想做一些额外的操作,比如记录函数的运行时间

标签: c# c++ using


【解决方案1】:

using 语句需要包裹在 #if DEBUG 块中

public static void Main(string[] args)
{
#if DEBUG
    using var test = new Test();
#endif

    Console.WriteLine("test");
}

您没有说明,但我认为您正在努力避免到处重复自己。可以将正在测试的代码作为参数传递:

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(() => Console.WriteLine("test"));
猜你喜欢
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
相关资源
最近更新 更多