但是如果第一个SqlCommand对象使用完毕以后调用一下Clear()方法,则该SqlParameter对象可以让其他SqlCommand重复使用.
class Program
{
static void Main(string[] args)
{
SqlParameter p1 = new SqlParameter("@p", 10);
F1(p1);
F2(p1);
Console.WriteLine("ok");
Console.ReadKey();
}
static void F1(SqlParameter p1)
{
//SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(p1);
//Type t = typeof(SqlParameter);
//FieldInfo info = t.GetField("_parent", BindingFlags.Instance | BindingFlags.NonPublic);
//object obj = info.GetValue(p1);
//Console.WriteLine(obj);
cmd.Dispose();
}
static void F2(SqlParameter p1)
{
//SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
//object obj1 = cmd.Parameters;
#region MyRegion
Type t = typeof(SqlParameter);
FieldInfo info = t.GetField("_parent", BindingFlags.Instance | BindingFlags.NonPublic);
//object obj = info.GetValue(p1);
//如果没有下面这句代码,则再次执行 cmd.Parameters.Add(p1);会报错!
//也就是说将p1._parent设置为null,则可以将一个SqlParameter参数添加到多个SqlCommand中。
info.SetValue(p1, null);
//Console.WriteLine(obj);
#endregion
//有了上面那句代码这里就不报错了。
cmd.Parameters.Add(p1);
cmd.Dispose();
}
}
也就是说当一个SqlParameter对象被某个SqlCommand对象添加到Parameters集合中的时候,SqlParameter对象自己会记录一下,被加到那个Parameters集合中了。如果下次再被其他SqlCommand对下加到Parameters集合时会检查_parent字段是否为null,如果不为null则抛出异常(System.ArgumentException ):
另一个 SqlParameterCollection 中已包含 SqlParameter。