Type反射遍历类的属性

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <!--实际生产中这里就是固定的配置方式(前面是实体属性,后面是约定验证方式)-->
    <add key="Setting1" value="name|sex|address,Account"/>
    <add key="Setting2" value="cardID|phone,Identity"/>
  </appSettings>
</configuration>

  

namespace ConsoleApplication1
{
    public class User
    {

        public string name { get; set; }
        public int age { get; set; }
        public string address { get; set; }
        public string cardID { get; set; }
        public string phone { get; set; }


    }

    public class VerfiyInfo
    {
        public string info { get; set; }
        public string method { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {


            User user = new User()
            {
                name = "Tom",
                address = "New York",
                age = 20,
                cardID = "3203821922222",
                phone = "18014925250"
            };
            VerfiyInfo verfiyInfo = GetVerfiy<VerfiyInfo>(user);

            Console.WriteLine(verfiyInfo.info + ":" + verfiyInfo.method);
            Console.ReadKey();
        }
        public static T GetVerfiy<T>(User model)
        {
            string appSetting = System.Configuration.ConfigurationSettings.AppSettings["Setting1"];
            if (string.IsNullOrEmpty(appSetting))
            {
                throw new Exception("无配置信息");
            }
            string[] strA = appSetting.Split(',');
            string strB = strA[0];
            string result = string.Empty;
            Type tp = model.GetType();
            PropertyInfo[] pros = tp.GetProperties();
            foreach (PropertyInfo pro in pros)
            {
                strB = strB.Replace(pro.Name, pro.GetValue(model).ToString());

            }
            string strJson = "{\"info\":\"" + strB + "\",\"method\":\"" + strA[1] + "\"}";
            T rModel = JsonConvert.DeserializeObject<T>(strJson);
            return rModel;

        }
    }
}

  

posted @ 2017-09-30 00:07  山顶洞外人  阅读(199)  评论(0编辑  收藏  举报