用了可能会被打死
//写着玩的,真用可能会被打死
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Transactions;
namespace Wrox.ProCSharp.Transactions
{
class Program
{
static void Main()
{
//模拟用户输入参数
User user = new User() { ID = 2, Sectors = new[] { "金融", "消费", "航天", "传统" } };
//原始语句
string str = "select * from User where 1=1 @Name @Sectors";
List<Tuple<BasicConfiguration>> tuples = new List<Tuple<BasicConfiguration>>();
//需求一:当用户输入名字的时候,通过名字查找
BasicConfiguration basicConfiguration = new BasicConfiguration()
{
Name = "@Name",//需要替换的名字
IsExecute = () => { return IsNotNull<User>(user, "Name"); },//是否进行替换,大部分操作都是进行非空判断,默认写个方法,能不能写一次就ok了,以后直接调用方法
ConcreteAction = () => { return " and name='" + user.Name + " '"; }//替换的结果
};
Tuple<BasicConfiguration> test1 = Tuple.Create<BasicConfiguration>(basicConfiguration);
tuples.Add(test1);
string aaa = StrReplace(str, tuples);
}
/// <summary>
/// 字符串替换,生成新的字符串
/// </summary>
/// <param name="Str"></param>
/// <param name="tuples"></param>
/// <returns></returns>
static string StrReplace(string Str, List<Tuple<BasicConfiguration>> tuples)
{
string str = Str;
foreach (var item in tuples)
{
if (item.Item1 != null) {
BasicConfiguration basicConfiguration = item.Item1 as BasicConfiguration;
if (basicConfiguration.IsExecute())
{
str = str.Replace(basicConfiguration.Name, basicConfiguration.ConcreteAction().ToString());
}
else {
str = str.Replace(basicConfiguration.Name, "");
}
}
}
return str;
}
/// <summary>
/// 判断非空
/// </summary>
/// <returns></returns>
static bool IsNotNull<T>(T t,params string[] AttrName) where T : new()
{
bool isbool = true;
foreach (string item in AttrName)
{
Type type = typeof(T);
var proInfo = type.GetProperty(item);
var result = proInfo.GetValue(t);
//string
if (proInfo.PropertyType.ToString() == "System.String")
{
if (result == null || result != "")
{
isbool = false;
break;
}
}
//[]
else if (proInfo.PropertyType.ToString().Contains("[]"))
{
if (result == null)
{
isbool = false;
break;
}
else
{
Array s = result as Array;
if (s.Length <= 0)
{
isbool = false;
break;
}
}
}
}
return isbool;
}
}
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string[] Sectors { get; set; }
}
/// <summary>
///
/// </summary>
public class BasicConfiguration
{
/// <summary>
/// 占位符名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 是否替换
/// </summary>
public Func<bool> IsExecute { get; set; }
/// <summary>
/// 替换结果
/// </summary>
public Func<object> ConcreteAction { get; set; }
}
}