如何作为参数传递时,我如何处置数据集

时间:2014-08-22 07:46:48

标签: c# code-analysis

我没有处理数据集的代码分析错误。当我将DataSet作为方法Test2的参数传递时,就会出现这种情况。 当我正在评论对Test2()的调用时,此错误被删除。 所以请帮我解决这个错误。

static DataSet TestMethod(DataSet s)
        {
            try
            {

                    try
                    {
                        if (s != null)
                        {
                            s = new DataSet();
                            //some other stuff....

                        }
                        **s = Test2(s);**  //This line causes Dispose code analysis error


                    }
                    catch (InvalidCastException)
                    {
                       throw;

                    }

                return s; 
            }
            catch (Exception)
            {
               throw;
            }

            finally
            {
                if (s!=null)
                {
                    s.Dispose();
                }

            }

        }

        static DataSet Test2(DataSet s)
        {
            try
            {
                //some stuff
            }
            catch (InvalidCastException)
            {


            }
            finally
            {
                s.Dispose();
            }
            return s;
        }

3 个答案:

答案 0 :(得分:2)

通常,您可以忽略指示您应该处置DataSet的错误。 DataSet实施IDisposable(与DataTable一样),但它不包含任何非托管资源:Should I Dispose() DataSet and DataTable?

但是,为什么要将DataSet作为参数传递给方法呢?为什么用Test2作为参数调用DataSet?为什么在尝试从该方法返回之前将其丢弃?

说实话,代码完全被破坏而且毫无意义。

通常你需要一种方法,如下所示:

static DataSet TestMethod()
{
    DataSet ds = new DataSet();

    using(var con = new SqlConnection("Connection-String"))
    using(var da = new SqlDataAdapter("SELECT t.* FROM TableName t ORDER BY t.Column", con))
        da.Fill(ds);

    return ds;
}

答案 1 :(得分:1)

这个警告并不是最糟糕的。您在DataSet方法中处置了Test2。你为什么那样做?它会使DataSet无用。即使返回它也是无用的,特别是当它与放入的实例相同时。

为什么不让Test2创建并返回新的DataSet而不是无意义地移动东西?

答案 2 :(得分:1)

你不应该处理你要归还的东西,并且在大多数情况下,你不应该处置某人传递给你的东西(你唯一会这样做)如果方法合同明确表明此方法负责清理,则处理它。坦率地说,我认为没有理由在所示的两种方法中处理完全。更正确的实现将是:

static DataSet TestMethod(DataSet s)
{

    if (s == null) // I'm assuming this was a typo, otherwise the
                   // input is completely ignored
    {
        s = new DataSet();
        //some other stuff....
    }
    Test2(s); // note you didn't handle the return value, so it
              // can't be important or relevent
    return s; // in case we just created it
}

static void Test2(DataSet s)
{
    //some stuff
}

您会发现完全没有处置;在有人传入现有DataSet的情况下,他们仍然希望它能够正常工作。在有人通过null的情况下 - 好吧 - 因为我们将新的作为结果递交给他们,处理它仍然没有意义。

如果调用者希望处置对象(在这种情况下不重要),那就是他们的工作

using(var ds = ...)
{
    // ...
    TestMethod(ds);
    // ...
}

或者可能是更具异国情调的建筑场景:

using(var rs = TestMethod(null))
{
    // ...
}
相关问题