注解属性的小例子

注解属性

注解属性为描述性信息,可用来描述类,方法,参数等。定义时使用,会被编译到dll 中,因此可在编程中动态获得这些描述信息。

小例子

/*
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.ComponentModel;
using System.Text;

*/
void Main()
{
	Student stu =new Student{
	  Name="张三",
	  Age=1,
	  HasPrerogation=true,
	  Gender=null,
	};
	stu.ConvertToInsertSql().Dump();
	
	IList<Student> stus =new List<Student>()
	{
	  stu,stu
	};
    DataTable dt= stus.ToDataTable();
	dt.Dump();
	
	dt.ToList<Student>().Dump();
	
}




[Serializable]
[Table(Name = "Student")]
public class Student{

  
    [Key]
    public string Id { get; set; }
	
	[Column(Name="Name",ColumnName="Name")]
    public string Name { get; set; }
	public int? Age { get; set; }
	public int? Gender { get; set; }
  
    public bool? HasPrerogation { get; set; }
} 

public static class Extensions{


   public static string ConvertToInsertSql<T>(this T obj)   where T:class
    {
        Type objT = obj.GetType();
        TableAttribute table = (TableAttribute)objT.GetCustomAttribute(CommonConsts.TableAttrbuiteType);
        if (string.IsNullOrWhiteSpace(table.Name))
            throw new Exception("请配置表名!");
        PropertyInfo[] properties = objT.GetProperties();

        StringBuilder sqli = new StringBuilder($@"INSERT  INTO  {table.Name}(");
        StringBuilder sqlv = new StringBuilder("               VALUES (");

        foreach (PropertyInfo property in properties)
        {
            object vaule = property.GetValue(obj);
            if (vaule == null)
            {
                var key = property.GetCustomAttributes(true).FirstOrDefault(u => u is KeyAttribute);
                if (key != null)
                {
                    sqli.Append(property.Name + ",");
                    sqlv.Append("'" + Guid.NewGuid().ToString("N") + "',");
                }
                continue;
            }
            var column =
                (ColumnAttribute)property.GetCustomAttributes(true).FirstOrDefault(u => u is ColumnAttribute);

            var name = property.Name;

            if (column != null && !string.IsNullOrWhiteSpace(column.Name))
                name = column.ColumnName;
            sqli.Append(name + ",");

            if (property.PropertyType.IsValueType && property.PropertyType != CommonConsts.DateTimeType &&
                property.PropertyType != CommonConsts.DateTimeNullType)
            {
                if (property.PropertyType == CommonConsts.BoolType ||
                    property.PropertyType == CommonConsts.BoolNullType)
                {
                    if (Convert.ToBoolean(property.GetValue(obj)))
                    {
                        sqlv.Append(1 + ",");
                    }
                    else
                    {
                        sqlv.Append(0 + ",");
                    }
                }
                else
                {
                    sqlv.Append(property.GetValue(obj) + ",");
                }
            }
            else
            {
                sqlv.Append("'" + property.GetValue(obj) + "',");

            }
        }
        sqli.Length = sqli.Length - 1;
        sqlv.Length = sqlv.Length - 1;
        sqli.Append(")");
        sqlv.Append(")");


        string sql = sqli + sqlv.ToString();
        return sql;
    }
	   public static DataTable ToDataTable<T>(this IEnumerable<T> data)
    {
        PropertyDescriptorCollection properties = 
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                 row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
	

    public static List<T> ToList<T>(this DataTable dt)
    {
        var columnNames = dt.Columns.Cast<DataColumn>()
            .Select(c => c.ColumnName.ToUpper())
            .ToList();

        var properties = typeof(T).GetProperties();
        var list = dt.AsEnumerable().Select(row =>
         {
             var objT = Activator.CreateInstance<T>();

             foreach (var pro in properties)
             {

                 if (columnNames.Contains(pro.Name.ToUpper()) && row[pro.Name].GetType() != CommonConsts.DbNullType)
                     pro.SetValue(objT, row[pro.Name]);
             }

             return objT;
         }).ToList();
        return list;
    }
}

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class KeyAttribute : Attribute
{ 
    public KeyAttribute() { }
}



//可扩展数据类型及长度,插入数据库时做约束性判断
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ColumnAttribute : Attribute 
{

    public string ColumnName { get; set; }
    public string Name { get; set; }
	public ColumnAttribute() { }
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]

public sealed class TableAttribute : Attribute
{

    public string Name { get; set; }

}



public static class CommonConsts
{

    public static Type BoolType = typeof(bool);
    public static Type BoolNullType = typeof(bool?);
    public static Type DateTimeType = typeof(DateTime);
    public static Type DateTimeNullType = typeof(DateTime?);
    public static Type DbNullType = typeof(DBNull);


    public static Type TableAttrbuiteType = typeof(TableAttribute);
    public static Type KeyAttrbuiteType = typeof(KeyAttribute);
}

执行效果

posted @ 2017-06-02 12:46  求道者  阅读(385)  评论(0)    收藏  举报