利用反射

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. 【第二组】Hunter-alpha版本发布报告

    Alpha版本测试报告 一  BUG汇总 1.暂时无法进行注册.(打算修复) 2.用户发布任务界面图标按钮存在显示bug.(打算修复) 3.主界面下拉菜单暂无内容,无法弹出.(打算修复) 二  场景测 ...

  2. Codeforces Round #442 (Div. 2) E Danil and a Part-time Job (dfs序加上一个线段树区间修改查询)

    题意: 给出一个具有N个点的树,现在给出两种操作: 1.get x,表示询问以x作为根的子树中,1的个数. 2.pow x,表示将以x作为根的子树全部翻转(0变1,1变0). 思路:dfs序加上一个线 ...

  3. Git安装配置和提交本地代码至Github,修改GitHub上显示的项目语言

    1. 下载安装git Windows版Git下载地址: https://gitforwindows.org/ 安装没有特别要求可以一路Next即可,安装完成后可以看到: 2. 创建本地代码仓库 打开G ...

  4. mysql出现“Incorrect key file for table”解决办法

    本文来自: https://www.cnblogs.com/zjoch/archive/2013/08/19/3267131.html 今天mysql突然出现以下错误: mysql> selec ...

  5. Jquery+H5验证数据(不是表单验证啊 )

    啥也不说了 直接上代码 1.我将所有需要验证的控件都加上了   required(类名自己定吧没啥讲究)  class 2.所有的控件都加上了 data-vname的H5自定义属性(名称自个定义吧) ...

  6. Android Toast 工具类

    android  中常用系统吐司工具类 package cn.yhq.utils; import android.content.Context; import android.widget.Toas ...

  7. CentOS 7 安装与卸载MySQL 5.7

    先介绍卸载 防止重装 yum方式 查看yum是否安装过mysql yum list installed mysql* 如或显示了列表,说明系统中有MySQL yum卸载 根据列表上的名字 yum re ...

  8. 51单片机学习笔记(郭天祥版)(6)——键盘的作业题、AD、DA、DS18B20(这里之后看清翔的补一下好了)

    A:analog,D:digital AD,就是模拟量转换为数字量,DA就是数字量转换为模拟量 为什么要转换? 单片机是数字芯片,内部只有0和1,没法表示模拟量 比如我们如果需要2.5V怎么办?其实是 ...

  9. 内置函数-fliter

    def is_odd(x): return x % 2 == 1 ret = filter(is_odd, [1,4,6,7,9]) print(ret) for i in ret: print(i) ...

  10. 52-2018 蓝桥杯省赛 B 组模拟赛(一)java

    最近蒜头君喜欢上了U型数字,所谓U型数字,就是这个数字的每一位先严格单调递减,后严格单调递增.比如 212212 就是一个U型数字,但是 333333, 9898, 567567, 313133131 ...