通过反射,获取类的属性

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;
    }
}

 

posted @ 2016-06-27 17:59  ChuckLu  阅读(390)  评论(0编辑  收藏  举报