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

      

  • 相关阅读:
    Docker——WIN7 安装 Docker实战与入门
    TensorFlow——dropout和正则化的相关方法
    TensorFlow——学习率衰减的使用方法
    TensorFlow——MNIST手写数据集
    TensorFlow——分布式的TensorFlow运行环境
    类加载器
    死亡的对象
    spring boot整合kafka
    Java验证手机号
    类生命周期
  • 原文地址:https://www.cnblogs.com/myloveblogs/p/7613291.html
Copyright © 2020-2023  润新知