C# 利用反射和特性 来做一些事情

特性代码:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TableAttribute : Attribute
{
private string _TableName;
/// <summary>
/// 映射的表名
/// </summary>
public string TableName
{
get { return _TableName; }
}
/// <summary>
/// 定位函数映射表名;
/// </summary>
/// <param name="table"></param>
public TableAttribute(string table)
{
_TableName = table;
} }
 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class FieldAttribute : Attribute
{
private string _Fields;
private string _Description;
private bool _IsEnable; public string Fields
{
get { return _Fields; } }
public bool IsEnable
{
get { return _IsEnable; } }
public string Description
{
get { return _Description; } }
public FieldAttribute(string fields, string description, bool isEnable)
{
_Fields = fields;
_Description = description;
_IsEnable = isEnable;
}
}

应用的模型类库

        [Key]
//[Field("表字段名称", "字段的说明", 是否在列表显示(true/false))]
[Field("ID", "用户标识",false)]
public string ID { get; set; } [Field("LoginName", "登录名",true)]
public string LoginName { get; set; } [Field("Password", "密码",false)]
public string Password { get; set; } [Field("Name", "姓名",true)]
public string Name { get; set; }

调用的代码:

        public static List<Columns> GetField_AttributeStr<T>() where T : class
{
List<Columns> columns = new List<Columns>();
Type t = GetPropertyType(typeof(T));
PropertyInfo[] Prs = t.GetProperties();
foreach (dynamic p in Prs)
{
object[] Fields = p.GetCustomAttributes(false);
foreach (dynamic attrs in Fields)
{
if (attrs is FieldAttribute)
{
FieldAttribute column = attrs as FieldAttribute;
var model = new Columns();
model.field = column.Fields;
model.title = column.Description;
model.sortable = false;
if (model.title == "排序" || model.title == "创建时间" || model.title == "修改时间")
{
model.sortable = true;
}
switch (column.IsEnable)
{
case true:
columns.Add(model);
break;
default:
break;
}
}
}
}
return columns;
}
上一篇:CCPC2018-湖南全国邀请赛 Solution


下一篇:ES6的一些常用特性