利用反射

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]遍历一个对象中所有的属性和值的更多相关文章

  1. c#遍历一个对象中所有的属性和值

    SpDictItem sp = GetCFHObject.GetSpItem("); PropertyInfo[] propertys = sp.GetType().GetPropertie ...

  2. jquery遍历标签中自定义的属性方法

    在开发中我们有时会对html标签添加属性,如何遍历处理 <ul> <li name="li1" sortid="nav_1">aaaaa ...

  3. 05. struts2中为Action属性注入值

    概述 struts2为Action中的属性提供了依赖注入功能 在struts2的配置文件中,我们可以很方便地为Action中的属性注入值.注意:属性必须提供get,set方法. 配置 <acti ...

  4. C#怎么遍历一个对象里面的全部属性?

    比如我现在有一个Student的对象,里面有属性stuName,stuAge,stuGender,我现在该怎么写循环才能遍历这几个属性? Student s=new...... foreach (Sy ...

  5. c# 遍历一个对象里面的全部属性

    比如我现在有一个Student的对象,里面有属性stuName,stuAge,stuGender,我现在该怎么写循环才能遍历这几个属性? Student s=new...... foreach (Sy ...

  6. 【XML】-- C#读取XML中元素和属性的值

    Xml是扩展标记语言的简写,是一种开发的文本格式. 啰嗦几句儿:老师布置的一个小作业却让我的脑细胞死了一堆,难的不是代码,是n多嵌套的if.foreach,做完这个,我使劲儿想:我一女孩,没有更多女孩 ...

  7. Java通过反射机制修改类中的私有属性的值

    首先创建一个类包含一个私有属性: class PrivateField{ private String username = "Jason"; } 通过反射机制修改username ...

  8. select 获取option中其他的属性的值

    <select name="tag_keys[]" id="category_type" required> <option value=&q ...

  9. Spring 中IOC(控制反转)&& 通过SET方式为属性注入值 && Spring表达式

    ### 1. Spring IoC IoC:Inversion of control:控制反转:在传统开发模式下,对象的创建过程和管理过程都是由开发者通过Java程序来实现的,操作权在开发者的Java ...

随机推荐

  1. Intellij IDEA常用快捷键介绍 Intellij IDEA快捷键大全汇总

    其他的快捷键还有很多,象Ctrl+G(跳转到指定行).Ctrl+F4(关闭当前编辑页面).Ctrl+F(搜索)等等,这些快捷键由于是各个编辑器都会提供的,而且定义的键位也都差不多,就没什么可说的了: ...

  2. jsonp现实跨域Ajax CORS

    浏览器有一个很重要的概念——同源策略(Same-Origin Policy).所谓同源是指,域名,协议,端口相同.不同源的客户端脚本(javascript.ActionScript)在没明确授权的情况 ...

  3. 给centos 7添加硬盘空间

    前言 今天在安装ambari的时候,制作amberi本地yum源的时候出现了一个问题,虚拟机的磁盘空间不足了,后来发现是因为这个节点之前本来只打算作为数据节点使用的,后来所以后来只给它分配了20G的硬 ...

  4. 关于Ajax异步请求(实时刷新)

    1.需求:想要做成动态实时刷新获取数据库的值 2.例子 3.代码逻辑: <script type="text/javascript"> var Seconds=1000 ...

  5. JAVA_04

    * a:局部代码块 * 在方法中出现:限定变量生命周期,及早释放,提高内存利用率 * b:构造代码块 (初始化块) * 在类中方法外出现:多个构造方法方法中相同的代码存放到一起,每次调用构造都执行,并 ...

  6. centos 7.2 同步北京时间 ,多台机器同步时间

    linux 系统没有北京时间,同步的是上海时间 linux 系统有两个时钟:一个是硬件时钟,即BIOS时间:另一个是系统时钟,是linux系统Kernel(内核)时间. 系统开启时,系统会读取硬件时间 ...

  7. Django Cache缓存系统学习--数据库缓存

    Django是动态网站,用户每一次请求页面,服务器都会执行以下操作:数据库查询.渲染模版.执行业务逻辑,最后生成用户可查看的页面.当访问量比较大的时候,会消耗掉大量的资源,这时候就会考虑到缓存问题. ...

  8. Game Engine Architecture 7

    [Game Engine Architecture 7] 1.SRT Transformations When a quaternion is combined with a translation ...

  9. Java框架spring Boot学习笔记(三):Controller的使用

    Controller注解介绍 @Controller:处理http请求 @RestController: Spirng4之后新加的注解,其实是一个组合注解等同于@ResponseBody和@Contr ...

  10. Centos 7 配置邮件发送

    一.环境 系统:centos 7 sendmail:sendmail.x86_64 0:8.14.7-5.el7 mailx版本:mailx-12.5-19.el7.x86_64 二.软件安装: 1. ...