检测ADO.net拼接字符串中非法字符

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace SaftSQL
{
public class SetterWrapper<TTarget, TValue>
{
private Action<TTarget, TValue> _setter;
public SetterWrapper(PropertyInfo propInfo)
{
if (propInfo == null)
throw new ArgumentNullException("propertyInfo");
if (!propInfo.CanWrite)
throw new NotSupportedException("属性是只读或Private Setter");
MethodInfo setMethod = propInfo.GetSetMethod(true);
_setter = (Action<TTarget, TValue>)Delegate.CreateDelegate(typeof(Action<TTarget, TValue>), null, setMethod);
}
public void SetValue(TTarget target, TValue val)
{
if (_setter != null)
{
_setter(target, val);
}
}
}
public class GetterWrapper<TTarget, TValue>
{
private Func<TTarget, TValue> _getter;
public GetterWrapper(PropertyInfo propInfo)
{
if (propInfo == null)
throw new ArgumentNullException("propertyInfo");
if (!propInfo.CanRead)
throw new NotSupportedException("属性是不可读或Private Getter");
MethodInfo getMethod = propInfo.GetGetMethod(true);
_getter = (Func<TTarget, TValue>)Delegate.CreateDelegate(typeof(Func<TTarget, TValue>), null, getMethod);
}
public TValue GetValue(TTarget target)
{
if (_getter != null)
{
return _getter(target);
}
return default(TValue);
}
}
public abstract class BaseQueryFilter
{
public void SafeSubmit<T>() where T : BaseQueryFilter
{
PropertyInfo[] propInfoArr = this.GetType().GetProperties();
foreach (var propInfo in propInfoArr)
{
if (propInfo.PropertyType == typeof(System.String))
{
GetterWrapper<T, string> getter = new GetterWrapper<T, string>(propInfo);
string val = getter.GetValue(this as T);
if (string.IsNullOrEmpty(val)) continue;
if (val.IndexOf("'") > -1)
{
SetterWrapper<T, string> setter = new SetterWrapper<T, string>(propInfo);
setter.SetValue(this as T, val.Replace("'", "''"));

}

}
}
}
}
}

 

用法:

class OrderFilter

{

public string ClientPhone{get;set;}

public string ClientName{get;set;}
}

 

void Main()

{

OrderFilter orderFilter = new OrderFilter()
{
ClientName="'123"
};

orderFilter.SafeSubmit();
}

转载于:https://www.cnblogs.com/zhshlimi/p/5066019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值