通过特性动态获取属性及值
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System;
namespace NPetshop.Domain
{
/***************************************************************************
*
* 功能: product实体类
* 作者: 李伟伟
* 日期: 2011-5-28
* 描述: 11111111111111111111111111
* *************************************************************************/
[Serializable]
public class productEntity
{
#region 属性
/// <summary>
/// 获取或设置Id字段的值 自增列 System.Int32
/// 数据库类型长度:int 大小:4 精度:10
/// </summary>
[Column("Id")]
public System.Int32 Id{get; set;}
/// <summary>
/// 获取或设置Name字段的值 System.String
/// 数据库类型长度:varchar 大小:50
/// </summary>
[Column("Name")]
public System.String Name{get; set;}
/// <summary>
/// 获取或设置UserId字段的值 System.Int32
/// 数据库类型长度:int 大小:4 精度:10
/// </summary>
[Column("UserId")]
public System.Int32 UserId{get; set;}
#endregion
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
/// <param name="name">Name</param>
/// <param name="userId">UserId</param>
public productEntity(System.String name,System.Int32 userId)
{
this.Name = name;
this.UserId = userId;
}
/// <summary>
/// 构造函数
/// </summary>
public productEntity()
{
this.Name = null;
this.UserId = 0;
}
#endregion
}
}
//特性
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace NPetshop.Domain
{
/// <summary>
/// 将类的属性与数据库表中的列相关联。
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public sealed class ColumnAttribute : System.Attribute
{
/// <summary>
/// 获取或设置列的名称。
/// </summary>
public string ColumnName { get; private set; }
/// <summary>
/// 获取或设置列的标题。
/// </summary>
public string ColumnCaption { get; private set; }
/// <summary>
/// 获取或设置列的类型。
/// </summary>
public SqlDbType ColumnType { get; private set; }
/// <summary>
/// 初始化 MagicStar.Entity.ColumnAttribute 类的一个新实例。
/// </summary>
/// <param name="columnCaption">表或视图的标题。</param>
/// <param name="columnName">表或视图的名称。</param>
/// <param name="columnType">类型。</param>
public ColumnAttribute(string columnName, string columnCaption, SqlDbType columnType)
{
ColumnName = columnName;
ColumnCaption = columnCaption;
ColumnType = columnType;
}
/// <summary>
/// 初始化 MagicStar.Entity.ColumnAttribute 类的一个新实例。
/// </summary>
/// <param name="columnCaption">表或视图的标题。</param>
/// <param name="columnName">表或视图的名称。</param>
/// <param name="columnType">类型。</param>
public ColumnAttribute(string columnName)
{
ColumnName = columnName;
}
}
}
///实现
productEntity _roductEntity = new productEntity();
_roductEntity.Id = 1;
_roductEntity.Name = "2";
Type type = _roductEntity.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Response.Write(type.GetProperty(property.Name).GetValue(_roductEntity, null));
Response.Write(property.Name + "");
}