zoukankan      html  css  js  c++  java
  • 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;
    
            }
        }
    }
    

      

  • 相关阅读:
    如何解决错误【selenium.common.exceptions.SessionNotCreatedException】
    VSFTP常用功能及参数配置
    ROS白名单服务端PHP脚本,客户端ROS脚本
    ocserver标准配置文件
    linux send与recv函数详解
    LINUX 恢复rm删除的文件
    C语言实现md5函数代码
    linux c语言获取CPU,内存,网速,磁盘使用,IO
    linux c语言fork socket 并发回射服务器
    杨惠兰不值得任何人付出
  • 原文地址:https://www.cnblogs.com/myloveblogs/p/7613291.html
Copyright © 2011-2022 走看看