1. 程式人生 > >Type反射遍歷類的屬性

Type反射遍歷類的屬性

for except ons apps work void esp onf version

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

        }
    }
}

  

Type反射遍歷類的屬性