C#-通过自定义注解反射生成SQL语句[转]

王朝学院·作者佚名  2016-08-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

转自http://blog.163.com/jong_cai/blog/static/87028045200902033553581/

----------------------------------------PRogram.cs----------------------------------------

using System;

using System.Collections.Generic;

using System.Text;

//反射命名空间

using System.Reflection;

namespace Test

{

class Program

{

static void Main(string[] args)

{

Student stu = new Student(1, "Jong_Cai", 21);

Insert(stu);

}

public static void Insert(Object obj)

{

String fileds = null;

String values = null;

Type type = obj.GetType();

//获取类名

String className = type.Name;

//获取所有公有属性

PropertyInfo[] info = type.GetProperties();

foreach (PropertyInfo var in info)

{

//取得属性的特性标签,false表示不获取因为继承而得到的标签

Object[] attr = var.GetCustomAttributes(false);

if (attr.Length > 0)

{

//从注解数组中取第一个注解(一个属性可以包含多个注解)

MyAttribute myattr = attr[0] as MyAttribute;

if (myattr.PrimaryKey == true)

{

continue;

}

}

fileds += var.Name + ",";

values += "'" + var.GetValue(obj, null) + "',";

}

fileds = fileds.Substring(0, fileds.Length - 1);

values = values.Substring(0, values.Length - 1);

String sql = "insert into {0}({1}) values({2})";

sql = String.Format(sql, className, fileds, values);

Console.WriteLine(sql);

}

}

}

-----------------------------------------------MyAttribute.cs---------------------------------------------------

using System;

using System.Collections.Generic;

using System.Text;

namespace Test

{

//自定义注解类

class MyAttribute: Attribute

{

public Boolean PrimaryKey = false;

public String Type = null;

}

}

-------------------------------------------Student.cs--------------------------------------------

using System;

using System.Collections.Generic;

using System.Text;

namespace Test

{

public class Student

{

private int _id;

[My(PrimaryKey = true, Type = "自动增长")] //自定义注解

public int Id

{

get { return _id; }

set { _id = value; }

}

private String _name;

[My(PrimaryKey = false, Type = "名字")] //自定义注解

public String Name

{

get { return _name; }

set { _name = value; }

}

private int _age;

[My(PrimaryKey = false, Type = "年龄")] //自定义注解

public int Age

{

get { return _age; }

set { _age = value; }

}

public Student(int id, String name, int age)

{

this._id = id;

this._name = name;

this._age = age;

}

}

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航