[问题] 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