[問題] 同一個變數複製值給兩個變數

看板C_Sharp作者 (阿洽)時間7年前 (2016/09/17 21:56), 7年前編輯推噓2(201)
留言3則, 3人參與, 最新討論串1/1
說明一下 我的原始資料是以 xml 存在於 table_content 裡的 column 裡,欄位名稱 content 為了要搜尋資料,我用 xml 將 content 裡的資料,用解析的方式寫成 view 但因為 view 的速度實在太慢,為了改善效能,每天晚上排程將 view 轉成 table 部份程式 tbCmd = new SqlCommand(); // 到 table 取值 vwCmd = new SqlCommand(); // 到 view 取值 Cmd = new SqlCommand(); List<string> vwCond = new List<string>(); List<string> tbCond = new List<string>(); List<string> Cond = new List<string>(); DataTable mainDt = new DataTable(); DataTable vwDt = new DataTable(); //開始指定共用的 sql 條件 if (txtVndrNm.Text != "") { Cond.Add("VENDOR_NAME LIKE '%' + @vendorNm + '%'"); Cmd.Parameters.Add("@vendorNm", SqlDbType.VarChar).Value = txtVndrNm.Text.Trim(); } // 把共用的 command text 分別複製給變數 vwCmd = Cmd; tbCmd = Cmd; // 把共用的 condition 分別複製給變數 vwCond = Cond; tbCond = Cond; //最後組裝 //view 的部份限定只搜尋符合今天日期的資料 -> 效能考量 vwCond.Add("BEGIN_TIME>=@vwbgTimeStart"); vwCmd.Parameters.Add("@vwbgTimeStart", SqlDbType.VarChar).Value = today + " 00:00"; vwCond.Add("BEGIN_TIME<=@vwbgTimeEnd"); vwCmd.Parameters.Add("@vwbgTimeEnd", SqlDbType.VarChar).Value = today + " 23:59"; vwCmd.CommandText = bindContition(todaySql, vwCond); tbCmd.CommandText = bindContition(oldSql, tbCond); 問題來了 在最後組裝的時候,我將 "限定資料範圍=今天" 的條件指派到 vwCond 但不知為何 tbCond 同樣收到了... 囧rz vwCond = Count = 3 tbCond = Count = 3 內容是一樣的 0 = "VENDOR_NAME LIKE '%' + @vendorNm + '%'" 1 = "BEGIN_TIME>=@vwbgTimeStart" 2 = "BEGIN_TIME<=@vwbgTimeEnd" tbCond 應該只有 count = 1 ,而且內容只有上面的 vendor_name 不知道哪裡出了問題 我 google 過傳值呼叫和傳址呼叫,但和我的問題好像沒有關係 .. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.132.93.23 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1474120561.A.AF1.html

09/17 22:23, , 1F
value type vs reference type
09/17 22:23, 1F
意思是 vwCond 和 tbCond 都被我宣告成 reference type 嗎? 但我看文件是說必須用 ref 才能宣告成 reference type ... = =a 是我誤解了嗎? 後來用這個方法處理 vwCmd = tbCmd = Cmd; List<string> vwCond = new List<string>(Cond); List<string> tbCond = new List<string>(Cond); 我知道應該是我的宣告是變成 reference type , 變數2 = 變數1 變數3 = 變數1 剛 google 到大概可以做出這樣的結論 想知道有沒比較好的做法 m(_ _)m ※ 編輯: aeolus0829 (220.132.93.23), 09/17/2016 23:06:49

09/18 00:24, , 2F
泛型就是參考型別。也可以用AddRange把相同條件加進去
09/18 00:24, 2F
啊.. 這個方法昨天看到的網頁好像也有提到 http://iblog.16806.com/?p=119

09/18 01:19, , 3F
把建立Command的方法拉到另一個函數去做
09/18 01:19, 3F
目前這個函數是判斷使用者有沒有輸入條件 有就丟到 list 裡 檢察完會再呼叫另一個函數將 list 組裝成 command text 我想你應該是這個意思? ※ 編輯: aeolus0829 (220.132.93.23), 09/18/2016 11:13:28
文章代碼(AID): #1NtKjnhn (C_Sharp)