[問題] 一些繼承的變數問題

看板C_Sharp (C#)作者時間13年前 (2012/09/09 09:10), 編輯推噓1(104)
留言5則, 2人參與, 最新討論串1/1
對不起. 小弟是Visual C#新手 目前小弟有一些困難想請教各位高手 現在我有一個公開的類別A,它有變數m_A public: bool m_A=false; 然後我有個類別B,有變數m_B且它公開繼承類別A 所以我寫成 public class B: A { public bool m_B=false; } 然後我在form1有宣告一個物件叫做object1_ 那object1_物件我宣告它是B類別的物件 B object1_=new B(); 我想在form1修改A與B類別內的變數 object1_.m_A=true; object1_.m_B=true; 而在form2也宣告物件object2_讀取m_A與m_B B object2_=new B(); bool openA=false; bool openB=false; openA=object2.m_A; openB=object2.m_B; 但是我真正執行後,發現變數m_A與m_B根本就是"false"啊 也就是說,他根本沒有修改到繼承裡的變數 請各位高手...我該用什麼方法才能改變呢~? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.71.102.63

09/09 09:35, , 1F
就說要貼能重現錯誤的完整code了 你貼的部分都沒問題
09/09 09:35, 1F

09/09 09:35, , 2F
錯的是你沒貼出來的其他部分
09/09 09:35, 2F

09/09 09:36, , 3F
繼承的變數就是這樣設值沒有錯 有設了就應該會變true
09/09 09:36, 3F
對不起,為了要簡化說明,我的程式碼會與例子有出入 ↓這是類別Parameter public class Parameter { public string filepath; public bool open_bin = false; //contorl open file as bin map public bool open_distribution = false; //contorl open file as distribution data } public class Function:Parameter { public bool binmap = false; //contorl function of map enabled public bool distribution = false; //contorl function of distribution enable public bool ampi_test = false; //contorl cp test as ampi public bool apce = false; //contorl cp test as apce //============================================================================== //↓這是form2上button click string filename = fileListBox1.FileName; Parameter file=new Parameter(); file.filepath = filename; file.open_bin = true; Function mfunction = new Function(); mfunction.binmap = true; mfunction.ampi_test=true; //============================================================================== //↓這是主程式form1 上button click Function mfunction = new Function(); Parameter file = new Parameter(); if (file.open_bin == true) { if (mfunction.binmap == true) { string filename = file.filepath; System.IO.StreamReader machinefile = new System.IO.StreamReader(filename); } else { MessageBox.Show("The Function have mistake,Please Check your data and datalog file!", "Caution", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Please Open File", "Caution", MessageBoxButtons.OK, MessageBoxIcon.Error); } 理論上來說,我form2按下button後 open_bin要=true,但我實際執行後 open_bin確還是 false ※ 編輯: chrishappy11 來自: 182.234.232.171 (09/09 09:46) ※ 編輯: chrishappy11 來自: 182.234.232.171 (09/09 09:47) ※ 編輯: chrishappy11 來自: 182.234.232.171 (09/09 09:54)

09/09 10:05, , 4F
你那兩個button_click裡面的Parameter跟Function是不同
09/09 10:05, 4F

09/09 10:06, , 5F
的物件 去google一下"變數生命周期" 就會了解了
09/09 10:06, 5F
文章代碼(AID): #1GI-nvXL (C_Sharp)
文章代碼(AID): #1GI-nvXL (C_Sharp)