通过反射,获取类的属性
Posted Chuck Lu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过反射,获取类的属性相关的知识,希望对你有一定的参考价值。
http://stackoverflow.com/questions/3723934/using-propertyinfo-to-find-out-the-property-type
https://www.codewars.com/kata/56c22c5ae8b139416c00175d/train/csharp
using StriveObjects; using System.Reflection; using System; public class Strive { public static string Match(Candidate c, Job j) { string str = string.Empty; var list = c.GetType().GetProperties(); foreach (PropertyInfo item in list) { Console.WriteLine($"{item} {item.PropertyType}"); } list = j.GetType().GetProperties(); foreach (PropertyInfo item in list) { Console.WriteLine($"{item} {item.PropertyType}"); } return str; } }
using System; public class Strive { public static bool Match(Candidate c, Job j) { var pro1 = c.GetType().GetProperty("MinSalary"); if (pro1 == null) { throw new ArgumentException(nameof(c)); } int min = Convert.ToInt32(pro1.GetValue(c, null)); var pro2 = j.GetType().GetProperty("MaxSalary"); if (pro2 == null) { throw new ArgumentException(nameof(j)); } int max = Convert.ToInt32(pro2.GetValue(j, null)); if (min == 0 || max == 0) { throw new ArgumentException(); } return min * 0.9 <= max; } }
以上是关于通过反射,获取类的属性的主要内容,如果未能解决你的问题,请参考以下文章