关于从使用块返回的最佳实践

发布于 2024-08-01 15:19:09 字数 278 浏览 11 评论 0 原文

哪种方法更好:从 using 语句内的方法返回一个值,或者在之前声明一个变量,在内部设置它并在之后返回它?

public int Foo()
{
  using(..)
  {
     return bar;
  }
}

或者

public int Foo()
{
  var b = null;
  using(..)
  {
    b = bar;
  }
  return b;
}

Which way is better practice: return a value from a method inside an using statement or declare a variable before, set it inside and return it after?

public int Foo()
{
  using(..)
  {
     return bar;
  }
}

or

public int Foo()
{
  var b = null;
  using(..)
  {
    b = bar;
  }
  return b;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

白芷 2024-08-08 15:19:10

来自使用声明 - MSDN

using 语句确保
即使发生异常也会调用 Dispose
当你调用方法时发生
在物体上。 您可以实现
将对象放入相同的结果
在 try 块内然后调用
在finally块中进行处理; 实际上,
这就是 using 语句的样子
由编译器翻译。

来自 try-finally(C# 参考)

finally 用于保证
执行语句代码块
无论前面的 try 块如何退出。

要回答您的问题,是的,可以从 using 语句返回。

From using Statement - MSDN

The using statement ensures that
Dispose is called even if an exception
occurs while you are calling methods
on the object. You can achieve the
same result by putting the object
inside a try block and then calling
Dispose in a finally block; in fact,
this is how the using statement is
translated by the compiler.

From the try-finally (C# Reference)

finally is used to guarantee a
statement block of code executes
regardless of how the preceding try block is exited.

To answer your question, yes its okay to return from a using statement.

绅刃 2024-08-08 15:19:10

我更喜欢第一个例子。 更少的变量,更少的代码行,更容易遵循,更容易维护......

public int Foo()
{
  using(..)
  {
     return bar;
  }
}

I prefer the first example. Fewer variables, fewer lines of code, easier to follow, easier to maintain...

public int Foo()
{
  using(..)
  {
     return bar;
  }
}
◇流星雨 2024-08-08 15:19:10

遵循“少即是多”原则(实际上只是 KISS 的变体),前者。 需要维护的代码行更少,语义没有变化,也没有可读性损失(可以说这种风格更容易阅读)。

Following the "less is more" principle (really just a variant of KISS), the former. There are fewer lines of code to maintain, no change in semantics and no loss of readability (arguably this style is easier to read).

罗罗贝儿 2024-08-08 15:19:10

第二种显然更好,你可以通过编写测试程序来验证它是否正常工作。

using 语句本身不能有值,这是一个限制。 假设您有一个名为 Open 的方法,它返回一个打开的 FileStream,并且您想要获取文件的长度:

Console.WriteLine(Open().Length);

这里的错误是您没有处理 <代码>文件流。 所以你必须写(类似于你的例子):

long length;

using (FileStream file = Open())
    length = file.Length;

Console.WriteLine(length);

但是用 简单的扩展方法,你可以这样写:

Console.WriteLine(Open().Use(file => file.Length));

漂亮又整洁,FileStream得到正确处理。

The second is clearly better, and you can verify that it works fine by writing a test program.

The using statement itself can't have a value, which is a limitation. Suppose you have a method called Open that returns an open FileStream, and you want to get the length of the file:

Console.WriteLine(Open().Length);

The bug there is that you aren't disposing the FileStream. So you have to write (similar to your example):

long length;

using (FileStream file = Open())
    length = file.Length;

Console.WriteLine(length);

But with a simple extension method, you can write this instead:

Console.WriteLine(Open().Use(file => file.Length));

Nice and neat, and the FileStream gets properly disposed of.

丑丑阿 2024-08-08 15:19:10

没有理由不这样做,因为 using 语句会转换为 try...finally 块,并且 finally 部分保证被执行(即使通过返回或未处理的异常)。

No reason not to since that using statement translates into a try...finally block and the finally part is guaranteed to be executed (even through a return or an unhandled exception).

荭秂 2024-08-08 15:19:10

这确实取决于个人喜好。 你会发现这个特定栅栏两边都有争论。 我个人更倾向于选择 1:尽快返回。 我相信它更好地表达了代码的意图; 没有理由坚持比你必须坚持的时间更长的时间。 如果您已完成所有工作,请返回。

有时,您将有多个可能的返回点,并且“方法结束”工作(日志记录、清理)可能会导致您得到单个返回语句。 这没什么可怕的,但是您通常可以在 finally 块中或使用面向方面编程中的方面来处理这些情况。

It really comes down to personal preference. You'll find arguments on both sides of this particular fence. Myself, I favor option 1: returning as soon as you can. I believe it expresses the intent of the code better; there's no reason to stick around longer than you have to. If you've completed all your work, return.

Sometimes, you'll have multiple possible return points, and "end-of-method" work (logging, cleanup) that might lead you to a single return statement. Nothing terrible about that, but you can often handle those situations in finally blocks or with aspects in aspect-oriented programming.

硬不硬你别怂 2024-08-08 15:19:10

我觉得第二个更好,

public int Foo()
{
  using(..)
  {
     return bar;
  }
}

使用这种方式时想到的一件事是,我们在 using 之间返回,所以对象(我们包装在 using 中)将被处置,答案是肯定的
因为 using 语句只是 try/finally 块的混合,所以从 try 块返回也可以。将计算返回表达式,然后执行 finally 块,然后该方法将返回。所以继续:)

I feel second one better

public int Foo()
{
  using(..)
  {
     return bar;
  }
}

One thing that arises in mind while using this way is that we are returning in between the using so will the object(that we have wrapped in using ) will get disposed ,the Answer is yes
because A using statement is just the mixture of try/finally block, it's fine to return from a try block too.The return expression will be evaluated, then the finally block will be executed, and the the method will return then.So go Ahead:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文