C# 如何为out参数创建dispose模式(消息IDE0068)
考虑这样的代码:C# 如何为out参数创建dispose模式(消息IDE0068),c#,.net,idisposable,C#,.net,Idisposable,考虑这样的代码: System.Data.DataTable dt=newdatatable() 类似这样的代码可能会在Visual Studio中的错误列表中给出一条消息:IDE0068使用推荐的dispose模式确保在所有路径上释放由“…”创建的对象:使用语句/声明或try/finally。因此,将其包装在using块中将确保处置dt实例 但是这个案子呢 SomeFunction(out DataTable dt) 在这种情况下如何处理dt?将其包装在using块中似乎不被接受: using
System.Data.DataTable dt=newdatatable()代码>
类似这样的代码可能会在Visual Studio中的错误列表中给出一条消息:IDE0068使用推荐的dispose模式确保在所有路径上释放由“…”创建的对象:使用语句/声明或try/finally。因此,将其包装在using块中将确保处置dt
实例
但是这个案子呢
SomeFunction(out DataTable dt)代码>
在这种情况下如何处理dt
?将其包装在using块中似乎不被接受:
using (DataTable dt = new DataTable()) {
/*dt needs to be initialised above otherwise this line won't compile*/
SomeFunction(out DataTable dt);
/* Above line: cannot use dt as ref or out variable because it is a 'using variable'*/
}
这里可以使用using
吗,或者我需要调用类似dt的东西吗?.Dispose()代码>在块的末尾?我很确定使用的块接受一个表达式,而不仅仅是一个声明,因此您可以在得到它后立即将其包装
SomeFunction(out var dt);
using (dt)
{
// Your logic here...
}
我很确定using
块接受一个表达式,而不仅仅是一个声明,因此您可以在得到它后立即将其包装
SomeFunction(out var dt);
using (dt)
{
// Your logic here...
}