在 C# 中模拟宏的最佳方法?

The best way to simulate macro in C#?

由于 C# 不支持宏,我正在寻找另一种(希望是优雅的)方法来编写一种 returns 不同类型值的方法,具体取决于条件编译符号。例如。 (如果可以使用宏)

#if ASYNC
  #define ASYNC_VOID async Task
#else
  #define ASYNC_VOID void
#endif

...

ASYNC_VOID Connect()
{
  ...
}
ASYNC_VOID Disconnect()
{
  ...
}
ASYNC_VOID Post()
{
  ...
}
ASYNC_VOID Delete()
{
  ...
}

我最好不要单独创建 Connect 和 ConnectAsync 方法,因为它们不需要同时在程序集中共存并且代码重复会过多(感谢 async/await 模型,sync和异步版本非常接近)。

我宁愿留下一个方法,让它以同步和异步模式编译。

有没有可能,或者我总是必须为每个方法都写这个?

#if ASYNC
  async Task
#else
  void
#endif
Connect()
{
  ...
}

这里。您有一个 C# preprocessor directives below. You'll also probably need this /define compiler directive 的示例,但请注意源代码开头的 #define。

你还有conditional methods

以后再也不用这个了。

#define abc   
namespace ConsoleApplication2
{
    class Class5
    {
        public
#if abc
 int
#else
    string
#endif
 Foo()
        {
#if abc
            return 7;
#else
    return "aa"
#endif
        }

        public void Bar()
        {
            #if abc
            int
#else
    string
#endif
 thing = Foo();
        }
    }
}