利用反射

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. autolayout原理

    Autolayout Engine根据视图间的约束关系得到一个线性方程组,求这个线性方程组的解即得到每个视图的位置信息.(x,y,width,height) 参考: https://www.jians ...

  2. Navicat Premium 12激活教程

    Navicat Premium 12激活教程 1.软件包的下载 百度云地址链接: 注册机:https://pan.baidu.com/s/1KzmCbVYcVoXt_t4osXk3Kw  提取码: q ...

  3. [原创] 扩展jquery-treegrid插件, 实现勾选功能和全删按钮.

    新上手一个项目, 因而正好想学习下bootstrap, 所以就采用asp.net mvc + bootstrap来做.  因为需要TreeGrid的控件, 本来想用easyUI.LingerUi.DW ...

  4. Taro开发写密码支付弹层

    在支付的时候弹出填写密码,模仿了支付宝支付填写密码.主要是利用遮罩的来实现.直接上代码吧. html设计,通过标记控制显示. { showPayPwdInput ? <View classNam ...

  5. unittest模块小结

    这次写的是unittest模块的测试用例,属于自动化的门槛,进去了基本算自动化入了门,测试内容很简单,模拟给url推送用户名.密码测试登录功能 先上代码: #login_test.py import ...

  6. wayne生产环境部署(360的容器发布平台-开源)

    参考文档 http://360yun.org/wayne/dev/develop-flow.html 使用rke部署k8s,详细过程见前面 文章,同时部署好kubectl 安装go yum insta ...

  7. 远程过程调用(RPC)

    在第二篇教程中我们介绍了如何使用工作队列(work queue)在多个工作者(woker)中间分发耗时的任务. 可是如果我们需要将一个函数运行在远程计算机上并且等待从那儿获取结果时,该怎么办呢?这就是 ...

  8. flock - 必应词典

    flock - 必应词典 美[flɑk]英[flɒk] v.聚集:群集:蜂拥 n.(羊或鸟)群:(尤指同类人的)一大群 网络羊群:大量:羊群,一群 变形复数:flocks:过去分词:flocked:现 ...

  9. PowerScript表达式

    运算符 算术运算符 双目运算符 运算符 名称 示例 说明 ^ 乘方 3^2   + 加 i_age+1   - 减 i_age - 1   * 乘 l_w*3   / 除 i_w/3   = 赋值 i ...

  10. jquery取出checkbox多选的值(带全选功能)

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...