如何通过“按值”传递SqlCommand [英] How Do I Pass a SqlCommand "by value"
本文介绍了如何通过“按值”传递SqlCommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个SqlCommand对象作为输入参数传递给一个方法。
我想传递SqlCommand" by value"所以对于
原始对象的任何更新都没有*反映在我方法中的对象中。
我该怎么做?
I want to pass a SqlCommand object as a input parameter to a method.
I want to pass the SqlCommand "by value" so that any updates to the
original object are *not* reflected in the object within my method.
How can I do this?
推荐答案
传递SqlCommand对象的克隆。
John Bailo写道:
Pass a clone of the SqlCommand object.
John Bailo wrote:
<我希望将SqlCommand对象作为输入参数传递给方法。
我想传递SqlCommand按值所以
原始对象的任何更新都不会*反映在我方法中的对象中。
我该怎么做?
I want to pass a SqlCommand object as a input parameter to a method.
I want to pass the SqlCommand "by value" so that any updates to the
original object are *not* reflected in the object within my method.
How can I do this?
你在谈论.MemberwiseClone()?
这似乎是一种受保护的方法,所以我无法访问它。
我还能如何克隆SqlCommand对象?
Ken Allen写道:
Are you talking about .MemberwiseClone() ?
That seems to be a protected method so I cannot access it.
How else can I clone the SqlCommand object?
Ken Allen wrote:
传递一个SqlCommand对象的克隆。 />
John Bailo写道:
Pass a clone of the SqlCommand object.
John Bailo wrote:
我想将SqlCommand对象作为输入参数传递给方法。
我想要传递SqlCommand按值所以对原始对象的任何更新都不会*反映在我方法中的对象中。
我该怎么做?
I want to pass a SqlCommand object as a input parameter to a method.
I want to pass the SqlCommand "by value" so that any updates to the
original object are *not* reflected in the object within my method.
How can I do this?
使用Clone():
class program
{
static void Main (string [] args)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText =" test";
cmd.Parameters.Add(" @ test",SqlDbType.BigInt);
SomeMethod((SqlCommand)cmd.Clone());
Console.WriteLine(cmd.Parameters.Count);
Console.WriteLine(cmd.CommandText);
Console.ReadLine() ;
}
static void SomeMethod(SqlCommand cmd)
{
cmd.CommandText = " test1";
cmd.Parameters.Clear();
}
}
结果:
1
测试
use Clone():
class Program
{
static void Main(string[] args)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "test";
cmd.Parameters.Add("@test", SqlDbType.BigInt);
SomeMethod((SqlCommand)cmd.Clone());
Console.WriteLine(cmd.Parameters.Count);
Console.WriteLine(cmd.CommandText);
Console.ReadLine();
}
static void SomeMethod(SqlCommand cmd)
{
cmd.CommandText = "test1";
cmd.Parameters.Clear();
}
}
result :
1
test
这篇关于如何通过“按值”传递SqlCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文