看板 C_Sharp 關於我們 聯絡資訊
各位好 我自己定義一個基礎類別BaseClass 和 衍生類別DerdivedClass public class BaseClass {} public class DerdivedClass : BaseClass {} 如下 我把BaseClass 轉成DerivedClass 會出錯 DerivedClass A2 = (DerivedClass)new BaseClass(); 但如果是底下寫法 就不會有錯 Button btn = (Button)this.FindControl("Button1"); FindControl所回傳的是Control 因為 Button : WebControl 且 WebControl : Control 所以 對Button來說 Control是基礎類別 Button是衍生類別 那為什麼 DerivedClass A2 = (DerivedClass)new BaseClass(); 會出錯 Button btn = (Button)this.FindControl("Button1"); 卻不會出錯呢? 程式碼 https://www.sendspace.com/file/gslh86 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.175.206.19 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1499582386.A.E8F.html
J002: A2 new出來後是BaseClass,不是DerivedClass,所以會出錯 07/09 14:52
J002: 但Button1本身就是一個Button,只是用FindControl找他的時候 07/09 14:53
J002: 會用Control這類別去找,所以從Control轉成Button時不會出錯 07/09 14:53
https://stackoverflow.com/questions/2889158/how-can-i-use-profilebase-class public class UserProfile : ProfileBase { public static UserProfile GetUserProfile(string username) { return Create(username) as UserProfile; } ............... } 謝謝 會有這個疑問 也是因為不了解為什麼Create()後可以轉UserProfile? 因為Create()後 回傳的type是ProfileBase 你上述Button1本身就是一個Button...這段敘述 我好像可以理解 但Create() 本身就是UserProfile嗎? 是這樣解釋嗎? 還是? ※ 編輯: kisha024 (1.175.206.19), 07/09/2017 20:01:11
s4300026: 這正常吧? 首先,冰箱是電器的一種,但冰箱不是電器, 07/09 21:27
s4300026: 這就是基底與衍伸的差別,然後你有個找電器的方法,找 07/09 21:27
s4300026: 到一個冰箱,然後你說它是一個冰箱,這樣有什麼問題嗎? 07/09 21:27
s4300026: 然後你的new是你有一個電器,但你說它是冰箱,那就會出 07/09 21:29
s4300026: 錯啦! 07/09 21:29
s4300026: 因為它可能是電視啊! 07/09 21:31
s4300026: 然後像我回傳值都是用object基底在溝通,然後再進行is,a 07/09 21:36
s4300026: s後處理 07/09 21:36
謝謝您的比喻 我覺得很貼切 但我的問題在於不知道那個方法是找電器的方法 還是找冰箱的方法? 從FindControl這個字眼上來看 的確是找控制項的方法 只是剛好找到Button 就說他是Button 但判斷一個方法要找的東西是什麼 該怎麼判斷呢? 請您看一下上面那個Create()方法ProfileBase Create()是要創造ProfileBase 只是剛好所創的是UserProfile 所以就說他是UserProfile 是這樣解釋嗎? ※ 編輯: kisha024 (1.175.206.19), 07/09/2017 22:18:38
vi000246: 這就跟float能轉int 但int不能轉float一樣的道理 07/09 22:36
vi000246: 可以google一下裝箱跟拆箱 07/09 22:37
IKAFIRE: float int互轉和裝拆箱無關,完全是另一個議題 07/09 23:34
shadow0326: 這是工廠方法的一種,Create和FindControl這兩個API都 07/10 02:21
shadow0326: 傳入你想要的物件名稱了,所以得到的會是子物件的實體 07/10 02:22
shadow0326: 以前前面的例子來說,假設電器行提供一個"買電器"的 07/10 02:23
shadow0326: API,你都說要買冰箱了,買到的電器就會是冰箱 07/10 02:23
s4300026: 有判斷的機制,叫做是否(is)和視為(as), 這是關鍵字喔~ 07/10 06:10
s4300026: create的傳入值就是問你要哪種物品 07/10 06:32
您的意思是 用is和as去判斷create()後回傳值是ProfileBase或UserProfile嗎? create的傳入值是個string 您的意思是 光靠傳入的string不同 就足以影響回傳的值是ProfileBase或UserProfile嗎?
s4300026: 我覺得應該是,但你可以試試看尋找別類控制項,然後轉 07/10 22:42
s4300026: 型成button看看會不會失敗 07/10 22:42
謝謝 很明顯會失敗
J002: 如果是您提到的stackoverflow中講的UserProfile,我想應該與 07/11 23:20
J002: 他後面提到的web.config有關,他有直接在web.config中設定 07/11 23:21
J002: profile的部份 07/11 23:21
J002: 抱歉,拖到今天才看到@@" 07/11 23:21
感謝 您太客氣了 ※ 編輯: kisha024 (60.251.130.137), 07/13/2017 16:48:14