[c#.net]遍历一个对象中所有的属性和值
利用反射
SpDictItem sp = GetCFHObject.GetSpItem("");
PropertyInfo[] propertys = sp.GetType().GetProperties();
foreach (PropertyInfo pinfo in propertys)
{
Response.Write("<br>" + pinfo.Name + "," + pinfo.GetValue(sp, null) + "<br>");
}
但是要判断可空类型的,可空类型的不能使用Property.GetValue(Model,null),如下
/// <summary>
/// C#反射遍历对象属性
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="model">对象</param>
public static void ForeachClassProperties<T>(T model)
{
Type t = model.GetType();
PropertyInfo[] PropertyList = t.GetProperties();
foreach (PropertyInfo item in PropertyList)
{
string name = item.Name;
object value = item.GetValue(model, null); Console.WriteLine(name); if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// If it is NULLABLE, then get the underlying type. eg if "Nullable<int>" then this will return just "int"
var columnType = item.PropertyType.GetGenericArguments()[];
Console.WriteLine(columnType);
}
else
{
Console.WriteLine(item.PropertyType.Name);
}
Console.WriteLine();
}
}
在我们的应用程序中我们使用类描述我们的业务对象,为我们产生一些报表之类的,那就依赖大量不同的对象,我们创建一个帮助方法来转换我们的业务对象,或是一个List的业务对象到DataTables.
由于数据库表中字段可为null,对应.net 2.0以后我们可用Nullable类型来实现,那当我们业务对象类中字段有null时,并需要转换为DataTable时,这个场景产生,你可能用到以下方法:
/// <summary>
/// Converts a Generic List into a DataTable
/// </summary>
/// <param name="list"></param>
/// <param name="typ"></param>
/// <returns></returns>
private DataTable GetDataTable(IList list, Type typ)
{
DataTable dt = new DataTable(); // Get a list of all the properties on the object
PropertyInfo[] pi = typ.GetProperties(); // Loop through each property, and add it as a column to the datatable
foreach (PropertyInfo p in pi)
{
// The the type of the property
Type columnType = p.PropertyType; // We need to check whether the property is NULLABLE
if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// If it is NULLABLE, then get the underlying type. eg if "Nullable<int>" then this will return just "int"
columnType = p.PropertyType.GetGenericArguments()[];
} // Add the column definition to the datatable.
dt.Columns.Add(new DataColumn(p.Name, columnType));
} // For each object in the list, loop through and add the data to the datatable.
foreach (object obj in list)
{
object[] row = new object[pi.Length];
int i = ; foreach (PropertyInfo p in pi)
{
row[i++] = p.GetValue(obj, null);
} dt.Rows.Add(row);
} return dt;
}
上面的代码的关键点:
- 用 PropertyType.IsGenericType 决定property是否是generic类型
- 用 ProprtyType.GetGenericTypeDefinition() == typeof(Nullable<>) 检测它是否是一个nullable类型
- 用 PropertyType.GetGenericArguments() 获取基类型。
下面让我们来应用一下:
public class Person
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime? DateOfDeath { get; set; }
} public class Example
{
public static DataTable RunExample()
{
Person edward = new Person() { Name = "Edward", DateOfBirth = new DateTime(, , ), DateOfDeath = new DateTime(, , ) };
Person margaret = new Person() { Name = "Margaret", DateOfBirth = new DateTime(, , ), DateOfDeath = null };
Person grant = new Person() { Name = "Grant", DateOfBirth = new DateTime(, , ), DateOfDeath = null }; List<Person> people = new List<Person>(); people.Add(edward);
people.Add(margaret);
people.Add(grant); DataTable dt = GetDataTable(people, typeof(Person)); return dt;
}
}
将返回的DataTable像下面的内容:

[c#.net]遍历一个对象中所有的属性和值的更多相关文章
- c#遍历一个对象中所有的属性和值
SpDictItem sp = GetCFHObject.GetSpItem("); PropertyInfo[] propertys = sp.GetType().GetPropertie ...
- jquery遍历标签中自定义的属性方法
在开发中我们有时会对html标签添加属性,如何遍历处理 <ul> <li name="li1" sortid="nav_1">aaaaa ...
- 05. struts2中为Action属性注入值
概述 struts2为Action中的属性提供了依赖注入功能 在struts2的配置文件中,我们可以很方便地为Action中的属性注入值.注意:属性必须提供get,set方法. 配置 <acti ...
- C#怎么遍历一个对象里面的全部属性?
比如我现在有一个Student的对象,里面有属性stuName,stuAge,stuGender,我现在该怎么写循环才能遍历这几个属性? Student s=new...... foreach (Sy ...
- c# 遍历一个对象里面的全部属性
比如我现在有一个Student的对象,里面有属性stuName,stuAge,stuGender,我现在该怎么写循环才能遍历这几个属性? Student s=new...... foreach (Sy ...
- 【XML】-- C#读取XML中元素和属性的值
Xml是扩展标记语言的简写,是一种开发的文本格式. 啰嗦几句儿:老师布置的一个小作业却让我的脑细胞死了一堆,难的不是代码,是n多嵌套的if.foreach,做完这个,我使劲儿想:我一女孩,没有更多女孩 ...
- Java通过反射机制修改类中的私有属性的值
首先创建一个类包含一个私有属性: class PrivateField{ private String username = "Jason"; } 通过反射机制修改username ...
- select 获取option中其他的属性的值
<select name="tag_keys[]" id="category_type" required> <option value=&q ...
- Spring 中IOC(控制反转)&& 通过SET方式为属性注入值 && Spring表达式
### 1. Spring IoC IoC:Inversion of control:控制反转:在传统开发模式下,对象的创建过程和管理过程都是由开发者通过Java程序来实现的,操作权在开发者的Java ...
随机推荐
- 如何在vs2015中编译并配置tesseract4.0
1)安装相关软件: 下载ccpan,把路径放到path(右击电脑,选择“属性”,选择左边的“高级系统设置”,选择“环境变量”,找到“系统变量”里面的“path”,点击“编辑”,选择右边的“新建”,输入 ...
- java面试题复习(六)
51.实现多线程的方法 一种是继承Thread类:另一种是实现Runnable接口.两种方式都要通过重写run()方法来定义线程的行为,推荐使用后者,因为Java中的继承是单继承,一个类有一个父类,如 ...
- nginx的命令
- CAtia_打开提示:许可证过期怎么办
CAtia_许可证过期怎么办:进计算机管理,点开服务和应用程序,点服务,找到DS License Server,在启动此服务的地方点启动,从而开启DS License Server.
- js中this的绑定规则及优先级
一. this绑定规则 函数调用位置决定了this的绑定对象,必须找到正确的调用位置判断需要应用下面四条规则中的哪一条. 1.1 默认绑定 看下面代码: function foo() { cons ...
- promise.then, setTimeout,await执行顺序问题
promise.then VS setTimeout 在chrome和node环境环境中均输出2, 3, 1, 先输出2没什么好说的,3和1顺序让人有些意外 原因: 有一个事件循环,但是任务队列可以有 ...
- Linux中 ./configure --prefix命令
源码的安装一般由3个步骤组成:配置(configure).编译(make).安装(make install),具体的安装方法一般作者都会给出文档,这里主要讨论配置(configure).Configu ...
- 《转》完美解决微信video视频隐藏控件和内联播放问题
地址:https://blog.csdn.net/xiao190128/article/details/81025378 var u = navigator.userAgent; var isAndr ...
- 云笔记项目-Spring事务学习-传播MANDATORY
接下来测试事务传播属性MANDATORY Service层 所有Service层实现类都设置事务传播属性为MANDATORY. LayerT层代码 package LayerT; import jav ...
- Java框架spring 学习笔记(十八):事务管理(xml配置文件管理)
在Java框架spring 学习笔记(十八):事务操作中,有一个问题: package cn.service; import cn.dao.OrderDao; public class OrderSe ...