从USING语句返回值(Return value from USING statement)

编程入门 行业动态 更新时间:2024-10-26 10:27:08
从USING语句返回值(Return value from USING statement)

最初,只有在任何问题(无论其类型如何)的情况下,此方法才会返回false 。 我想知道如果应用using语句打破了逻辑,如果异常

以这种方式从使用语句中返回值是否可行:

try { Measurements.DeleteAllMeasurements(ID); string query = "DELETE FROM `Narz` WHERE `NAZk_1_ID`=@NAZ_ID"; using(OleDbConnection strukturaConnection = new OleDbConnection(CommonConnectionString + DbPath + strStructureMdb)) { using (OleDbCommand command = new OleDbCommand(query, strukturaConnection);) { command.Parameters.Add("@NAZ_ID", OleDbType.Numeric, 50); command.Parameters["@NAZ_ID"].Value = ID; command.ExecuteNonQuery(); return true; } } } catch (Exception ex) { Logger.LogError(ex); return false; }

或者我应该以另一种方式回报错误

Originally this method returns false only in case of ANY problems regardless of their type. I'm wondering will applying using statement break the logic if exception

Is it ok to return true value from the using statement in this manner:

try { Measurements.DeleteAllMeasurements(ID); string query = "DELETE FROM `Narz` WHERE `NAZk_1_ID`=@NAZ_ID"; using(OleDbConnection strukturaConnection = new OleDbConnection(CommonConnectionString + DbPath + strStructureMdb)) { using (OleDbCommand command = new OleDbCommand(query, strukturaConnection);) { command.Parameters.Add("@NAZ_ID", OleDbType.Numeric, 50); command.Parameters["@NAZ_ID"].Value = ID; command.ExecuteNonQuery(); return true; } } } catch (Exception ex) { Logger.LogError(ex); return false; }

Or I should return false in another way?

最满意答案

所有使用语句都会隐式地在代码块的末尾调用实例的IDisposable.Dispose()实现。

除非你正在返回一个引用,并且Dispose()方法恰好操作它,那么这两个问题是完全不相关的。

简而言之,使用声明中返回的值是无关紧要的。

编辑:关于你的方法“应该返回”:我们没有足够的信息来知道这一点。 我们甚至不知道该方法的名称是什么。 我们不知道应用该方法的其他对象或方面。 返回值应该对调用者有意义,并有效地传达操作结果。

All the using statement does is implicitly call the instance's implementation of IDisposable.Dispose() at the end of the code block.

Unless you are returning a reference and the Dispose() method happens to manipulate it, then the two concerns are completely unrelated.

In short, it doesn't matter what value you return from within a using statement.

Edit: About what your method "should return": We don't have enough information to know this. We don't even know what the name of the method is. And we don't know by what other objects or aspects of the application the method will be used. The return value should be meaningful to its caller, and effectively communicate the result of the operation.

更多推荐

本文发布于:2023-04-27 22:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329052.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   返回值   statement   Return

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!