[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 ...
随机推荐
- ORM版学员管理系统 2
学生信息管理 展示学生信息 URL部分 url(r'^student_list/', app01_views.student_list, name="student_list"), ...
- 软件工程个人作业四--alpha阶段个人总结
个人总结 (1)个人总结 类型 具体技能和面试问题 现在的回答 毕业找工作的时间 语言 最拿手的计算机语言之一,代码量多少 C语言相对熟悉一点 软件实现 你有没有在别的代码的基础上改进,你是怎么读懂别 ...
- 每日算法之递推排序(P1866 编号)
兔子也是数字控:每个兔子都有自己喜欢的数字区间,找出能让所有兔子都满意的组合. 将所有兔子喜欢的序号按从小到大排序,此时如果小序号的兔子选择了一个数字,则之后的兔子只要排除排在它之前的兔子数(由于已经 ...
- 模拟PLC 的圆弧插补方式在VC中绘制圆弧
最近同事想让要做一个绘图的控件.VC里面的画弧函数Arc需要提供外接矩形的坐标.同事觉得不好用,他更习惯圆弧插补的那种方式.于是看了看圆弧插补的东西.其实这种画弧方式就是提供圆弧的起点.终点和半径来画 ...
- Navicat Premium 12激活教程
Navicat Premium 12激活教程 1.软件包的下载 百度云地址链接: 注册机:https://pan.baidu.com/s/1KzmCbVYcVoXt_t4osXk3Kw 提取码: q ...
- BASH_SOURCE
在C/C++中,__FUNCTION__常量记录当前函数的名称.有时候,在日志输出的时候包含这些信息是非常有用的.而在Bash中,同样有这样一个常量FUNCNAME,但是有一点区别是,它是一个数组而非 ...
- TabLayout占不满屏幕所有宽度
<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_wi ...
- 爬虫之pyspider
1.简单的介绍 pyspider是由国人binux编写的强大的网络爬虫系统,其GitHub地址为 https://github.com/binux/pyspider 官方文档地址为 http://do ...
- c语言作业01-分支、顺序结构
1.本章思考总结 1.1思维导图 1.2本章学习体会及代码量学习体会 1.2.1学习体会 这一个星期算是我学习c语言的起点,因为暑假没有提前自学c语言,所以一上课时会觉得比较吃力也难以跟上其他大部分同 ...
- linux 安装java环境
1.检查是否安装或者linux系统自带jdK 命令:java -version 查找JDK相关包是否被安装: rpm -qa |grep jdk rpm -qa |grep gcj 删除JDK相关包: ...