[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 ...
随机推荐
- __name__ __main__ 作用
1 __name__ 在自己文件下面执行 就显示__main__ 2 如果__name__是在其他文件里面,然后通过当前文件调用到其他文件执行,就会显示的当前文件路劲的文件名结果: if __name ...
- JavaScript值全等判断
作为开发员,很多时候拿到数据之后都是要做数据判断,比较特别的情况就是我们需要做数组判断和对象判断,经常的我们就array === array ,object === object;但是可惜是我们得到的 ...
- zabbix通过agent添加监控项的步骤
1.确定要监控的对象的指标 2.在agent端上,把如何具体获取指标写成shell脚本,并放在一个和其它agent端统一的位置上 3.在agent端上,自定义监控项key值,配置zabbix_agen ...
- gson格式化参数 对象转Map
前台传json到后台接收: String params = request.getParameters("paramtes"); Map<String, Map<St ...
- Redis的Errorlog或者启动日志(错误日志)的配置
Errorlog或者是运行日志是任何一个软件的运行中异常诊断必看的文件之一,折腾Redis的过程中以为有默认的错误日志(或启动日志),不过一直没有发现类似的日志文件,在看了默认的配置文件之后,发现Re ...
- Linux 基本使用
1.mkdir 创建文件夹 mkdir filename; 2.touch 创建文件 touch file.txt; 3.chmod 变更文件或目录的权限 chmod -R u+x ./;
- Go语言编程读书笔记:Go channel(2)
单向channel 概念 单向channel是只能用于发送或者接收数据,channel本身必然是同时支持读写,否则根本没法用.假如一个channel只能读,那么肯定只会是空的,因为你没有机会向里面写数 ...
- 计算kdj
import pandas as pd def KDJ_K(df,n=9): df['highest'] = df['high'].rolling(n).max() df['lowest' ...
- coderwarrior 查看程序大小 Code Size
https://mcuoneclipse.com/2012/09/24/code-size-information-with-gcc-for-armkinetis/
- SqlServer卡慢解决办法
SqlServer活动监视器调成1s刷新间隔 查看资源等待 (1)memory(内存)占用高时-->加内存(2)latch(业级锁)(并发量大时产生)-->调整cpu核心数可能解决(不一定 ...