【问题标题】:What is the best way to use using?使用 using 的最佳方式是什么?
【发布时间】:2020-06-19 13:37:32
【问题描述】:

什么是最好的使用方式?

代码1:

public async Task<IActionResult> EditEmployeePicture(string userId)
{
    using IClubRep current = new ClubRep(_db);
    var data = await current.CurrentUserData(user.Id);
}

代码2:

public async Task<IActionResult> EditEmployeePicture(string userId)
{
    using (IClubRep current = new ClubRep(_db))
    {
        var data = await current.CurrentUserData(user.Id);
    }
}

代码3:

private IClubRep Club { get; set; }
.
.
.
public async Task<IActionResult> EditEmployeePicture(string userId)
{
    Club = new ClubRep(_db);
    var data = await Club.CurrentUserData(user.Id);
}

您认为使用 using 的最佳方式是什么? 对系统的压力最小。

【问题讨论】:

  • code1code2 编译为完全相同的 IL。使用对您和您的团队更有利的任何东西。 code3 无法处理 ClubRep 并且不应使用(假设 IClubRep 确实是 IDisposable,否则 code1code2 将无法编译)。在每次调用EditEmployeePicture 时,都会泄露一个新实例。即使它以某种方式被重复使用,也不清楚应该由谁处理。一般来说,您希望一次性对象的范围尽可能小。
  • 代码 1 和代码 2 相同。代码 3 不调用 Dispose()
  • 使用代码 2,您可以控制何时处理对象。首选 imo。
  • @spender:您假设的示例不正确,并且没有演示问题中的场景。 using declarations (introduced in C# 8) 与单行 using 表达式不同。使用using 声明引入的值将被放置在变量作用域的末尾,在这种情况下是方法的末尾(即与code2 相同)。
  • @TaW:OTOH 代码在早期版本的 C# 中无法合法编译,因为不支持该语法,因此假设这不是一个很大的飞跃。 :-P

标签: c# asp.net-core using


【解决方案1】:

使用 code1:您的一次性生活直到方法结束,因为编译器生成的 try/catch/finally 块包含所有代码。使用 code2:它只存在到 using 块的末尾,因为编译器会为该部分生成单独的 try/catch/finally。

在您的示例中,它们完全相同,但如果您在此之后有大量代码:using IClubRep current = new ClubRep(_db);,那么一次性用品的寿命会稍长一些。

【讨论】:

  • 代码 1 在到达行尾的分号时处理(并导致编译器警告)。当我们到达下一行时,对象已经被释放。 dotnetfiddle.net/ZBcz36
  • @spender 您的示例不是 OP 示例的适当模拟。在 using 语句之后不要使用一次性用品。 See this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 2012-02-04
  • 2014-09-17
  • 2020-11-26
  • 2011-12-10
  • 2016-04-12
  • 1970-01-01
相关资源
最近更新 更多