Posted on 2008-06-28 23:38
玄铁剑 阅读(384)
评论(0) 编辑 收藏 引用 所属分类:
asp.net
首先声明一个带一个属性的Attribute,用这个属性来存操作符
[AttributeUsage(AttributeTargets.Field)] //此属性只能用在Field上
public class OpAttribute : Attribute
{
private string _op = string.Empty;
public OpAttribute(string op)
{
_op = op;
}
public string Name
{
get { return _op; }
set { _op = value; }
}
}
然后在查询条件的类中加上这些Attribute
public class AttributeClass
{
[OpAttribute("=")]
public int MyProperty;
[OpAttribute("=")]
public string aa;
[OpAttribute("like")]
public string bb;
}
然后再调用一个组合sql语句的方法
AttributeClass ac = new AttributeClass();
ac.MyProperty = 11;
ac.aa = "abcd";
ac.bb = "ddd";
string sql="1=1";
Type type = typeof(AttributeClass);
foreach (System.Reflection.FieldInfo fieldInfo in type.GetFields())
{
foreach (Attribute at in fieldInfo.GetCustomAttributes(true))
{
OpAttribute att = at as OpAttribute;
if (att != null)
{
sql += " and " + fieldInfo.Name +" "+ att.Name+" "+ fieldInfo.GetValue(ac);
}
}
}