[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 ...
随机推荐
- c#switch语句的用法
switch条件语句是一种很常用的选择语句,它与if条件语句不同,它只针对某个表达式的值作出判断,从而决定执行哪一段代码. switch条件语句用到的关键字: switch case break de ...
- php进阶--菜鸟之路
希望有所帮助! 第一阶段:基础阶段(基础PHP程序员) 重点:把LNMP搞熟练(核心是安装配置基本操作) 目标:能够完成基本的LNMP系统安装,简单配置维护:能够做基本的简单系统的PHP开发:能够在P ...
- 使用 nodeJs 开发微信公众号(上传图片)
在给用户发送消息中涉及到的素材(图片.视频.音频.文章等)需要事先传到微信服务器,然后获得媒体id(media_id),然后把 media_id 传递给用户 上传分上传临时素材(只保存三天)和上传永久 ...
- Matplotlib-多图合并显示
Subplot 多合一显示 均匀图中图 不均匀图中图 # 均匀图中图 # matplotlib 是可以组合许多的小图, 放在一张大图里面显示的. 使用到的方法叫作 subplot. # 使用impor ...
- Mongodb到mysql数据库的数据迁移(Java,Windows)
运行环境为windows 测试过260万的数据表,迁移大概要10分钟左右,当然肯定和网络,字段大小什么的有关系. 遇到的坑和注意点都用紫色标记了(对,就是我大乃团的高冷紫--Nogizaka 46) ...
- python学习Day13 函数的嵌套定义、global、nonlocal关键字、闭包及闭包的运用场景、装饰器
复习 1.函数对象:函数名 => 存放的是函数的内存地址1)函数名 - 找到的是函数的内存地址2)函数名() - 调用函数 => 函数的返回值 eg:fn()() => fn的返回值 ...
- Object备忘录
1.Object.assign(target,...source) 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.它将返回目标对象. 2.Object.create()方法创建一个新对 ...
- boss推荐文章
20170216 --- 谁是你的下一个客户?国内 B2B Predictive Marketing 公司浅探(中)https://zhuanlan.zhihu.com/p/25257243?refe ...
- superset在 centos 7安装运行
参考:1.http://blog.csdn.net/u014729236/article/details/76302888?locationNum=2&fps=1 2.https://www. ...
- Tomcat 配置MySQL连接池
<!--配置mysql数据库的连接池, 需要做的额外步骤是将mysql的Java驱动类放到tomcat的lib目录下 maxIdle 连接池中最多可 ...