[問題] method 代入 Attributes

作者: abc95007 (別理我)   2018-11-09 10:58:27
請問要如何從 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");
}
}
}
作者: J002 (阿里山 我來了XD~)   2018-11-09 11:10:00
Constrcutor ?
作者: testPtt (測試)   2018-11-09 12:22:00
p.GetType().GetProperty(propertyName).GetValue(p,null
作者: ATPS4869 (ATPS4869)   2018-11-09 12:23:00
member expressions
作者: abc95007 (別理我)   2018-11-09 13:24:00
感謝 已解決
作者: jass970991 (半糖綠假面超人)   2018-11-09 14:49:00
建議不要 一般使用上很少用到需要解偶合這麼徹底的例子 而且IDE還不一定找的到 不考慮多加一個方法去返回你要的數值嗎?有點誤會你的意思了 但我還是建議你 不要這樣寫 你這樣會讓耦合度變高 不是好事 最好還是弄個方法出來

Links booklink

Contact Us: admin [ a t ] ucptt.com