看板 C_Sharp 關於我們 聯絡資訊
請問要如何從 method 去帶入 class 的屬性? 如以下範例 感謝~ class person { public string weight = "50"; public string height = "150"; } class Program { // 由 item 可以選擇 weight或是 height public void printItemValue(person p, string item) { Console.WriteLine(p.item); } static void Main(string[] args) { person A = new person(); person B = new person(); person C = new person(); person D = new person(); List<person> persons = new List<person>() { A , B, C, D}; foreach (person p in persons) { printItemValue(p, "weight"); } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.217.96.219 ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1541732312.A.333.html
J002: Constrcutor ? 11/09 11:10
testPtt: p.GetType().GetProperty(propertyName).GetValue(p,null 11/09 12:22
ATPS4869: member expressions 11/09 12:23
abc95007: 感謝 已解決 11/09 13:24
jass970991: 建議不要 一般使用上很少用到需要解偶合這麼徹底的例 11/09 14:49
jass970991: 子 而且IDE還不一定找的到 不考慮多加一個方法去返回 11/09 14:49
jass970991: 你要的數值嗎? 11/09 14:49
jass970991: 有點誤會你的意思了 但我還是建議你 不要這樣寫 你這 11/09 19:26
jass970991: 樣會讓耦合度變高 不是好事 最好還是弄個方法出來 11/09 19:26