Type反射遍历类的属性
Posted MR_CHW
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } } }
以上是关于Type反射遍历类的属性的主要内容,如果未能解决你的问题,请参考以下文章