将C#8.0转换为C#7.0

问题描述 投票:1回答:1

我正要使用下面的C#代码。

await using (var producerClient = new EventHubProducerClient(ConnectionString, EventHubName))
{
    using EventDataBatch eventBatch = await producerClient.CreateBatchAsync();
    eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(eventData)));
    await producerClient.SendAsync(eventBatch);
}

但是在构建服务器中,由于上面是C#8.0代码,因此构建失败,并且构建服务器仅支持C#7.0代码。有人可以帮我将上面的代码从C#8.0转换为C#7.0,因为我无法使其工作吗?

c# asynchronous async-await using c#-7.0
1个回答
4
投票

从长远来看,您当然最好更新构建服务器。无论如何,您迟早都需要这样做。

C#8.0具有using declarations,它将转换为:

using var x = ...;
...

进入此:

using (var x = ...)
{
  ...
}

此代码中的其他C#8.0功能是await usingwhich transforms代码,如下所示:

await using (var x = ...)
{
  ...
}

类似于以下内容:

var x = ...;
try
{
  ...
}
finally
{
  await x.DisposeAsync();
}

手动应用这两种转换都会给您:

var producerClient = new EventHubProducerClient(ConnectionString, EventHubName);
try
{
  using (EventDataBatch eventBatch = await producerClient.CreateBatchAsync())
  {
    eventBatch.TryAdd(new EventData(Encoding.UTF8.GetBytes(eventData)));
    await producerClient.SendAsync(eventBatch);
  }
}
finally
{
  await producerClient.DisposeAsync();
}
© www.soinside.com 2019 - 2024. All rights reserved.