C#通过反射获取相应的字段和值
代码比较简单,只作为简单的例子参考
首先先看运行的代码:
class Program { static void Main(string[] args) { UserInfo userInfo = new UserInfo(); userInfo.ID = 1; userInfo.Name = "bailey"; userInfo.CreateDate = DateTime.Now; userInfo.Number = Convert.ToDecimal(456.6467); string values = string.Empty; foreach (System.Reflection.PropertyInfo p in userInfo.GetType().GetProperties()) { if (p.PropertyType == typeof(string)) { values += string.Format("{0}='{1}', ", p.Name, p.GetValue(userInfo)); } if (p.PropertyType == typeof(int)|| p.PropertyType == typeof(uint)) { values += string.Format("{0}={1},", p.Name, p.GetValue(userInfo)); } if (p.PropertyType == typeof(DateTime)) { values += string.Format("{0}='{1}', ", p.Name, p.GetValue(userInfo)); } if (p.PropertyType == typeof(decimal) || p.PropertyType == typeof(double)|| p.PropertyType == typeof(float)) { values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo)); } if (p.PropertyType == typeof(bool)) { values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo)); } if (p.PropertyType == typeof(sbyte)) { values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo)); } if (p.PropertyType == typeof(byte) || p.PropertyType == typeof(short) || p.PropertyType == typeof(ushort) ) { values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo)); } if (p.PropertyType == typeof(long) || p.PropertyType == typeof(ulong)) { values += string.Format("{0}={1}, ", p.Name, p.GetValue(userInfo)); } // values +=string.Format( "{0}={1},", p.Name, p.GetValue(userInfo)); // Console.WriteLine("Name:{0} Value:{1}", p.Name, p.GetValue(userInfo)); } Console.WriteLine(values); Console.ReadLine(); } }
再看对象:
class UserInfo { public int ID { get; set; } public string Name { get; set; } public DateTime? CreateDate { get; set; } public decimal? Number { get; set; } public bool IsUse { get; set; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)