日期:2014-05-18  浏览次数:20710 次

函数改变了代入参数的值,是怎么做到的呢
public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
  {
  using (SqlConnection connection = new SqlConnection(factorychoice()))
  {
  SqlCommand cmd = new SqlCommand();
  PrepareCommand(cmd, connection, null, SQLString, cmdParms);
  using (SqlDataAdapter da = new SqlDataAdapter(cmd))
  {
  DataSet ds = new DataSet();
  try
  {
  da.Fill(ds, "ds");
  cmd.Parameters.Clear();
  }
  catch (System.Data.SqlClient.SqlException ex)
  {
  throw new Exception(ex.Message);
  }
  return ds;
  }
  }
  }
以上的代码高人所写,我所纳闷的是下面这几句代码
 SqlCommand cmd = new SqlCommand();
  PrepareCommand(cmd, connection, null, SQLString, cmdParms);
cmd的值经过PrepareCommand函数后,里面的参数改变了,这是为什么呢, PrepareCommand函数如下
 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
  {
  if (conn.State != ConnectionState.Open)
  conn.Open();
  cmd.Connection = conn;
  cmd.CommandText = cmdText;
  if (trans != null)
  cmd.Transaction = trans;
  cmd.CommandType = CommandType.Text;//cmdType;
  if (cmdParms != null)
  {
  foreach (SqlParameter parameter in cmdParms)
  {
  if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  (parameter.Value == null))
  {
  parameter.Value = DBNull.Value;
  }
  cmd.Parameters.Add(parameter);
  }
  }
  }

我用控制台模拟了一下,并未改变,代码如下
  class Program
  {
  static void Main(string[] args)
  {
  int i = 3;
  addvale(i);
  Console.Write(i.ToString());
  Console.ReadKey();
  }
  public static void addvale(int ii)
  {
  ii = ii + 5;
  }
  }
高人帮忙解答一下,谢谢.

------解决方案--------------------
需要改传入参数,前边需要加ref
举个例子
C# code

class Program
    {
        static void Main(string[] args)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("1111");
            StringBuilder builder2 = builder;

            Change1(builder);
            Console.WriteLine("Change1");
            Console.WriteLine(object.ReferenceEquals(builder,builder2).ToString());
            Console.WriteLine(builder.ToString());
            Console.WriteLine(builder2.ToString());

            Change2(ref builder);
            Console.WriteLine("Change2");
            Console.WriteLine(object.ReferenceEquals(builder, builder2).ToString());
            Console.WriteLine(builder.ToString());
            Console.WriteLine(bu