mirror of
https://gitee.com/langsisi_admin/serein-flow
synced 2026-03-03 00:00:49 +08:00
将部分节点基类与表达式工具类从nodeflow迁移到library,重写了环境与工作台的交互,解耦节点的获取,下一部分将尝试远程登录环境编辑流程。
This commit is contained in:
@@ -29,6 +29,8 @@ namespace Serein.Library.Utils
|
||||
result = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 从枚举值的 BindValueAttribute 特性中 获取绑定的参数(用于绑定了某些内容的枚举值)
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
|
||||
{
|
||||
public class BoolConditionResolver : SereinConditionResolver
|
||||
{
|
||||
public enum Operator
|
||||
{
|
||||
/// <summary>
|
||||
/// 是
|
||||
/// </summary>
|
||||
Is
|
||||
}
|
||||
|
||||
public Operator Op { get; set; }
|
||||
public bool Value { get; set; }
|
||||
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
|
||||
if (obj is bool boolObj)
|
||||
{
|
||||
return boolObj == Value;
|
||||
/*switch (Op)
|
||||
{
|
||||
case Operator.Is:
|
||||
return boolObj == Value;
|
||||
}*/
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
|
||||
{
|
||||
public class MemberConditionResolver<T> : SereinConditionResolver where T : struct, IComparable<T>
|
||||
{
|
||||
//public string MemberPath { get; set; }
|
||||
public ValueTypeConditionResolver<T>.Operator Op { get; set; }
|
||||
public object TargetObj { get; set; }
|
||||
public T Value { get; set; }
|
||||
|
||||
public string ArithmeticExpression { get; set; }
|
||||
public T RangeEnd { get; internal set; }
|
||||
public T RangeStart { get; internal set; }
|
||||
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
//object? memberValue = GetMemberValue(obj, MemberPath);
|
||||
|
||||
|
||||
if (TargetObj is T typedObj)
|
||||
{
|
||||
return new ValueTypeConditionResolver<T>
|
||||
{
|
||||
RangeStart = RangeStart,
|
||||
RangeEnd = RangeEnd,
|
||||
Op = Op,
|
||||
Value = Value,
|
||||
ArithmeticExpression = ArithmeticExpression,
|
||||
}.Evaluate(typedObj);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//private object? GetMemberValue(object? obj, string memberPath)
|
||||
//{
|
||||
// string[] members = memberPath[1..].Split('.');
|
||||
// foreach (var member in members)
|
||||
// {
|
||||
// if (obj == null) return null;
|
||||
// Type type = obj.GetType();
|
||||
// PropertyInfo? propertyInfo = type.GetProperty(member);
|
||||
// FieldInfo? fieldInfo = type.GetField(member);
|
||||
// if (propertyInfo != null)
|
||||
// obj = propertyInfo.GetValue(obj);
|
||||
// else if (fieldInfo != null)
|
||||
// obj = fieldInfo.GetValue(obj);
|
||||
// else
|
||||
// throw new ArgumentException($"Member {member} not found in type {type.FullName}");
|
||||
// }
|
||||
// return obj;
|
||||
//}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
|
||||
{
|
||||
public class MemberStringConditionResolver : SereinConditionResolver
|
||||
{
|
||||
public string MemberPath { get; set; }
|
||||
|
||||
public StringConditionResolver.Operator Op { get; set; }
|
||||
|
||||
public string Value { get; set; }
|
||||
|
||||
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
object memberValue;
|
||||
if (!string.IsNullOrWhiteSpace(MemberPath))
|
||||
{
|
||||
memberValue = GetMemberValue(obj, MemberPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
memberValue = obj;
|
||||
}
|
||||
|
||||
if (memberValue is string strObj)
|
||||
{
|
||||
return new StringConditionResolver
|
||||
{
|
||||
Op = Op,
|
||||
Value = Value
|
||||
}.Evaluate(strObj);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private object GetMemberValue(object obj, string memberPath)
|
||||
{
|
||||
//string[] members = memberPath[1..].Split('.');
|
||||
string[] members = memberPath.Substring(1).Split('.');
|
||||
foreach (var member in members)
|
||||
{
|
||||
|
||||
if (obj is null) return null;
|
||||
|
||||
Type type = obj.GetType();
|
||||
PropertyInfo propertyInfo = type.GetProperty(member);
|
||||
FieldInfo fieldInfo = type.GetField(member);
|
||||
if (propertyInfo != null)
|
||||
obj = propertyInfo.GetValue(obj);
|
||||
else if (fieldInfo != null)
|
||||
obj = fieldInfo.GetValue(obj);
|
||||
else
|
||||
throw new ArgumentException($"Member {member} not found in type {type.FullName}");
|
||||
}
|
||||
|
||||
return obj;
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static string GetArithmeticExpression(string part)
|
||||
{
|
||||
int startIndex = part.IndexOf('[');
|
||||
int endIndex = part.IndexOf(']');
|
||||
if (startIndex >= 0 && endIndex > startIndex)
|
||||
{
|
||||
return part.Substring(startIndex + 1, endIndex - startIndex - 1);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
|
||||
{
|
||||
public class PassConditionResolver : SereinConditionResolver
|
||||
{
|
||||
public Operator Op { get; set; }
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
/*return Op switch
|
||||
{
|
||||
Operator.Pass => true,
|
||||
Operator.NotPass => false,
|
||||
_ => throw new NotSupportedException("不支持的条件类型")
|
||||
};*/
|
||||
switch (Op)
|
||||
{
|
||||
case Operator.Pass:
|
||||
return true;
|
||||
case Operator.NotPass:
|
||||
return false;
|
||||
default:
|
||||
throw new NotSupportedException("不支持的条件类型");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public enum Operator
|
||||
{
|
||||
Pass,
|
||||
NotPass,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
|
||||
{
|
||||
public class StringConditionResolver : SereinConditionResolver
|
||||
{
|
||||
public enum Operator
|
||||
{
|
||||
/// <summary>
|
||||
/// 出现过
|
||||
/// </summary>
|
||||
Contains,
|
||||
/// <summary>
|
||||
/// 没有出现过
|
||||
/// </summary>
|
||||
DoesNotContain,
|
||||
/// <summary>
|
||||
/// 相等
|
||||
/// </summary>
|
||||
Equal,
|
||||
/// <summary>
|
||||
/// 不相等
|
||||
/// </summary>
|
||||
NotEqual,
|
||||
/// <summary>
|
||||
/// 起始字符串等于
|
||||
/// </summary>
|
||||
StartsWith,
|
||||
/// <summary>
|
||||
/// 结束字符串等于
|
||||
/// </summary>
|
||||
EndsWith
|
||||
}
|
||||
|
||||
public Operator Op { get; set; }
|
||||
|
||||
public string Value { get; set; }
|
||||
|
||||
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
if (obj is string strObj)
|
||||
{
|
||||
/*return Op switch
|
||||
{
|
||||
Operator.Contains => strObj.Contains(Value),
|
||||
Operator.DoesNotContain => !strObj.Contains(Value),
|
||||
Operator.Equal => strObj == Value,
|
||||
Operator.NotEqual => strObj != Value,
|
||||
Operator.StartsWith => strObj.StartsWith(Value),
|
||||
Operator.EndsWith => strObj.EndsWith(Value),
|
||||
_ => throw new NotSupportedException("不支持的条件类型"),
|
||||
};*/
|
||||
|
||||
switch (Op)
|
||||
{
|
||||
case Operator.Contains:
|
||||
return strObj.Contains(Value);
|
||||
case Operator.DoesNotContain:
|
||||
return !strObj.Contains(Value);
|
||||
case Operator.Equal:
|
||||
return strObj == Value;
|
||||
case Operator.NotEqual:
|
||||
return strObj != Value;
|
||||
case Operator.StartsWith:
|
||||
return strObj.StartsWith(Value);
|
||||
case Operator.EndsWith:
|
||||
return strObj.EndsWith(Value);
|
||||
default:
|
||||
throw new NotSupportedException("不支持的条件类型");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using Serein.Library.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression.Resolver
|
||||
{
|
||||
public class ValueTypeConditionResolver<T> : SereinConditionResolver where T : struct, IComparable<T>
|
||||
{
|
||||
public enum Operator
|
||||
{
|
||||
/// <summary>
|
||||
/// 不进行任何操作
|
||||
/// </summary>
|
||||
Node,
|
||||
/// <summary>
|
||||
/// 大于
|
||||
/// </summary>
|
||||
GreaterThan,
|
||||
/// <summary>
|
||||
/// 小于
|
||||
/// </summary>
|
||||
LessThan,
|
||||
/// <summary>
|
||||
/// 等于
|
||||
/// </summary>
|
||||
Equal,
|
||||
/// <summary>
|
||||
/// 大于或等于
|
||||
/// </summary>
|
||||
GreaterThanOrEqual,
|
||||
/// <summary>
|
||||
/// 小于或等于
|
||||
/// </summary>
|
||||
LessThanOrEqual,
|
||||
/// <summary>
|
||||
/// 在两者之间
|
||||
/// </summary>
|
||||
InRange,
|
||||
/// <summary>
|
||||
/// 不在两者之间
|
||||
/// </summary>
|
||||
OutOfRange
|
||||
}
|
||||
|
||||
public Operator Op { get; set; }
|
||||
public T Value { get; set; }
|
||||
public T RangeStart { get; set; }
|
||||
public T RangeEnd { get; set; }
|
||||
|
||||
public string ArithmeticExpression { get; set; }
|
||||
|
||||
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
|
||||
var evaluatedValue = obj.ToConvert<T>();
|
||||
if (!string.IsNullOrEmpty(ArithmeticExpression))
|
||||
{
|
||||
evaluatedValue = SerinArithmeticExpressionEvaluator<T>.Evaluate(ArithmeticExpression, evaluatedValue);
|
||||
}
|
||||
|
||||
switch (Op)
|
||||
{
|
||||
case Operator.GreaterThan:
|
||||
return evaluatedValue.CompareTo(Value) > 0;
|
||||
case Operator.LessThan:
|
||||
return evaluatedValue.CompareTo(Value) < 0;
|
||||
case Operator.Equal:
|
||||
return evaluatedValue.CompareTo(Value) == 0;
|
||||
case Operator.GreaterThanOrEqual:
|
||||
return evaluatedValue.CompareTo(Value) >= 0;
|
||||
case Operator.LessThanOrEqual:
|
||||
return evaluatedValue.CompareTo(Value) <= 0;
|
||||
case Operator.InRange:
|
||||
return evaluatedValue.CompareTo(RangeStart) >= 0 && evaluatedValue.CompareTo(RangeEnd) <= 0;
|
||||
case Operator.OutOfRange:
|
||||
return evaluatedValue.CompareTo(RangeStart) < 0 || evaluatedValue.CompareTo(RangeEnd) > 0;
|
||||
}
|
||||
return false;
|
||||
|
||||
//if (obj is T typedObj)
|
||||
//{
|
||||
// numericValue = Convert.ToDouble(typedObj);
|
||||
// numericValue = Convert.ToDouble(obj);
|
||||
// if (!string.IsNullOrEmpty(ArithmeticExpression))
|
||||
// {
|
||||
// numericValue = SerinArithmeticExpressionEvaluator.Evaluate(ArithmeticExpression, numericValue);
|
||||
// }
|
||||
|
||||
// T evaluatedValue = (T)Convert.ChangeType(numericValue, typeof(T));
|
||||
|
||||
// /*return Op switch
|
||||
// {
|
||||
// Operator.GreaterThan => evaluatedValue.CompareTo(Value) > 0,
|
||||
// Operator.LessThan => evaluatedValue.CompareTo(Value) < 0,
|
||||
// Operator.Equal => evaluatedValue.CompareTo(Value) == 0,
|
||||
// Operator.GreaterThanOrEqual => evaluatedValue.CompareTo(Value) >= 0,
|
||||
// Operator.LessThanOrEqual => evaluatedValue.CompareTo(Value) <= 0,
|
||||
// Operator.InRange => evaluatedValue.CompareTo(RangeStart) >= 0 && evaluatedValue.CompareTo(RangeEnd) <= 0,
|
||||
// Operator.OutOfRange => evaluatedValue.CompareTo(RangeStart) < 0 || evaluatedValue.CompareTo(RangeEnd) > 0,
|
||||
// _ => throw new NotSupportedException("不支持的条件类型")
|
||||
// };*/
|
||||
// switch (Op)
|
||||
// {
|
||||
// case Operator.GreaterThan:
|
||||
// return evaluatedValue.CompareTo(Value) > 0;
|
||||
// case Operator.LessThan:
|
||||
// return evaluatedValue.CompareTo(Value) < 0;
|
||||
// case Operator.Equal:
|
||||
// return evaluatedValue.CompareTo(Value) == 0;
|
||||
// case Operator.GreaterThanOrEqual:
|
||||
// return evaluatedValue.CompareTo(Value) >= 0;
|
||||
// case Operator.LessThanOrEqual:
|
||||
// return evaluatedValue.CompareTo(Value) <= 0;
|
||||
// case Operator.InRange:
|
||||
// return evaluatedValue.CompareTo(RangeStart) >= 0 && evaluatedValue.CompareTo(RangeEnd) <= 0;
|
||||
// case Operator.OutOfRange:
|
||||
// return evaluatedValue.CompareTo(RangeStart) < 0 || evaluatedValue.CompareTo(RangeEnd) > 0;
|
||||
// }
|
||||
//}
|
||||
//return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
775
Library/Utils/SereinExpression/SereinConditionParser.cs
Normal file
775
Library/Utils/SereinExpression/SereinConditionParser.cs
Normal file
@@ -0,0 +1,775 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Serein.Library.Utils;
|
||||
using Serein.NodeFlow.Tool.SereinExpression.Resolver;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.Design;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression
|
||||
{
|
||||
/// <summary>
|
||||
/// 字符串工具类
|
||||
/// </summary>
|
||||
public static class StringHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Net低版本无法引入Skip函数,所以使用扩展方法代替
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentNullException"></exception>
|
||||
public static IEnumerable<T> MySkip<T>(this IEnumerable<T> source, int count)
|
||||
{
|
||||
if (source == null)
|
||||
throw new ArgumentNullException(nameof(source));
|
||||
|
||||
int skipped = 0;
|
||||
foreach (var item in source)
|
||||
{
|
||||
if (skipped++ >= count)
|
||||
yield return item;
|
||||
}
|
||||
}
|
||||
|
||||
public static string JoinStrings(string[] parts, int startIndex, int count, char separator)
|
||||
{
|
||||
if (parts == null)
|
||||
throw new ArgumentNullException(nameof(parts));
|
||||
|
||||
if (startIndex < 0 || startIndex >= parts.Length || count < 0 || startIndex + count > parts.Length)
|
||||
throw new ArgumentOutOfRangeException();
|
||||
|
||||
// 复制需要的部分到新的数组
|
||||
string[] subArray = new string[count];
|
||||
Array.Copy(parts, startIndex, subArray, 0, count);
|
||||
|
||||
// 使用 string.Join 连接
|
||||
return string.Join(separator.ToString(), subArray);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
public class SereinConditionParser
|
||||
{
|
||||
public static bool To<T>(T data, string expression)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(expression))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var parse = ConditionParse(data, expression);
|
||||
var result = parse.Evaluate(data);
|
||||
return result;
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static SereinConditionResolver ConditionParse(object data, string expression)
|
||||
{
|
||||
if (expression.StartsWith(".")) // 表达式前缀属于从上一个节点数据对象获取成员值
|
||||
{
|
||||
return ParseObjectExpression(data, expression);
|
||||
}
|
||||
else
|
||||
{
|
||||
return ParseSimpleExpression(data, expression);
|
||||
}
|
||||
|
||||
|
||||
//bool ContainsArithmeticOperators(string expression)
|
||||
//{
|
||||
// return expression.Contains('+') || expression.Contains('-') || expression.Contains('*') || expression.Contains('/');
|
||||
//}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取计算表达式的部分
|
||||
/// </summary>
|
||||
/// <param name="part"></param>
|
||||
/// <returns></returns>
|
||||
private static string GetArithmeticExpression(string part)
|
||||
{
|
||||
int startIndex = part.IndexOf('[');
|
||||
int endIndex = part.IndexOf(']');
|
||||
if (startIndex >= 0 && endIndex > startIndex)
|
||||
{
|
||||
return part.Substring(startIndex + 1, endIndex - startIndex - 1);
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取对象指定名称的成员
|
||||
/// </summary>
|
||||
private static object GetMemberValue(object obj, string memberPath)
|
||||
{
|
||||
//string[] members = memberPath[1..].Split('.');
|
||||
string[] members = memberPath.Substring(1).Split('.');
|
||||
|
||||
foreach (var member in members)
|
||||
{
|
||||
if (obj is null) return null;
|
||||
Type type = obj.GetType();
|
||||
PropertyInfo propertyInfo = type.GetProperty(member);
|
||||
FieldInfo fieldInfo = type.GetField(member);
|
||||
if (propertyInfo != null)
|
||||
obj = propertyInfo.GetValue(obj);
|
||||
else if (fieldInfo != null)
|
||||
obj = fieldInfo.GetValue(obj);
|
||||
else
|
||||
throw new ArgumentException($"Member {member} not found in type {type.FullName}");
|
||||
}
|
||||
return obj;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 解析对象表达式
|
||||
/// </summary>
|
||||
private static SereinConditionResolver ParseObjectExpression(object data, string expression)
|
||||
{
|
||||
var parts = expression.Split(' ');
|
||||
string operatorStr = parts[0]; // 获取操作类型
|
||||
string valueStr; //= string.Join(' ', parts, 1, parts.Length - 1);
|
||||
string memberPath;
|
||||
Type type;
|
||||
object targetObj;
|
||||
|
||||
// 尝试获取指定类型
|
||||
int typeStartIndex = expression.IndexOf('<');
|
||||
int typeEndIndex = expression.IndexOf('>');
|
||||
if (typeStartIndex + typeStartIndex == -2)
|
||||
{
|
||||
// 如果不需要转为指定类型
|
||||
memberPath = operatorStr;
|
||||
targetObj = SerinExpressionEvaluator.Evaluate("@get " + operatorStr, data, out _);
|
||||
//targetObj = GetMemberValue(data, operatorStr);
|
||||
type = targetObj.GetType();
|
||||
operatorStr = parts[1].ToLower(); //
|
||||
valueStr = string.Join(" ", parts.Skip(2));
|
||||
}
|
||||
else
|
||||
{
|
||||
// 类型语法不正确
|
||||
if (typeStartIndex >= typeEndIndex)
|
||||
{
|
||||
throw new ArgumentException("无效的表达式格式");
|
||||
}
|
||||
memberPath = expression.Substring(0, typeStartIndex).Trim();
|
||||
string typeStr = expression.Substring(typeStartIndex + 1, typeEndIndex - typeStartIndex - 1)
|
||||
.Trim().ToLower(); // 手动置顶的类型
|
||||
|
||||
// 对象取值表达式
|
||||
parts = expression.Substring(typeEndIndex + 1).Trim().Split(' ');
|
||||
if (parts.Length == 3)
|
||||
{
|
||||
operatorStr = parts[1].ToLower(); // 操作类型
|
||||
valueStr = string.Join(" ", parts.Skip(2)); // 表达式值
|
||||
}
|
||||
else
|
||||
{
|
||||
operatorStr = parts[0].ToLower(); // 操作类型
|
||||
valueStr = string.Join(" ", parts.Skip(1)); // 表达式值
|
||||
}
|
||||
Type tempType;
|
||||
|
||||
switch (typeStr)
|
||||
{
|
||||
case "bool":
|
||||
tempType = typeof(bool);
|
||||
break;
|
||||
case "float":
|
||||
tempType = typeof(float);
|
||||
break;
|
||||
case "decimal":
|
||||
tempType = typeof(decimal);
|
||||
break;
|
||||
case "double":
|
||||
tempType = typeof(double);
|
||||
break;
|
||||
case "sbyte":
|
||||
tempType = typeof(sbyte);
|
||||
break;
|
||||
case "byte":
|
||||
tempType = typeof(byte);
|
||||
break;
|
||||
case "short":
|
||||
tempType = typeof(short);
|
||||
break;
|
||||
case "ushort":
|
||||
tempType = typeof(ushort);
|
||||
break;
|
||||
case "int":
|
||||
tempType = typeof(int);
|
||||
break;
|
||||
case "uint":
|
||||
tempType = typeof(uint);
|
||||
break;
|
||||
case "long":
|
||||
tempType = typeof(long);
|
||||
break;
|
||||
case "ulong":
|
||||
tempType = typeof(ulong);
|
||||
break;
|
||||
// 如果需要支持 nint 和 nuint
|
||||
// case "nint":
|
||||
// tempType = typeof(nint);
|
||||
// break;
|
||||
// case "nuint":
|
||||
// tempType = typeof(nuint);
|
||||
// break;
|
||||
case "string":
|
||||
tempType = typeof(string);
|
||||
break;
|
||||
default:
|
||||
tempType = Type.GetType(typeStr);
|
||||
break;
|
||||
}
|
||||
type = tempType ?? throw new ArgumentException("对象表达式无效的类型声明");
|
||||
if (string.IsNullOrWhiteSpace(memberPath))
|
||||
{
|
||||
targetObj = Convert.ChangeType(data, type);
|
||||
}
|
||||
else
|
||||
{
|
||||
targetObj = GetMemberValue(data, memberPath);// 获取对象成员,作为表达式的目标对象
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#region 解析类型 int
|
||||
if (type.IsValueType)
|
||||
{
|
||||
//return GetValueResolver(type, valueStr, operatorStr, parts);
|
||||
}
|
||||
if (type == typeof(int))
|
||||
{
|
||||
var op = ParseValueTypeOperator<int>(operatorStr);
|
||||
if (op == ValueTypeConditionResolver<int>.Operator.InRange || op == ValueTypeConditionResolver<int>.Operator.OutOfRange)
|
||||
{
|
||||
var temp = valueStr.Split('-');
|
||||
if (temp.Length < 2)
|
||||
throw new ArgumentException($"范围无效:{valueStr}。");
|
||||
int rangeStart = int.Parse(temp[0], CultureInfo.InvariantCulture);
|
||||
int rangeEnd = int.Parse(temp[1], CultureInfo.InvariantCulture);
|
||||
return new MemberConditionResolver<int>
|
||||
{
|
||||
Op = op,
|
||||
RangeStart = rangeStart,
|
||||
RangeEnd = rangeEnd,
|
||||
TargetObj = targetObj,
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0]),
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
int value = int.Parse(valueStr, CultureInfo.InvariantCulture);
|
||||
|
||||
|
||||
return new MemberConditionResolver<int>
|
||||
{
|
||||
TargetObj = targetObj,
|
||||
//MemberPath = memberPath,
|
||||
Op = ParseValueTypeOperator<int>(operatorStr),
|
||||
Value = value,
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0])
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
#region 解析类型 double
|
||||
else if (type == typeof(double))
|
||||
{
|
||||
double value = double.Parse(valueStr, CultureInfo.InvariantCulture);
|
||||
return new MemberConditionResolver<double>
|
||||
{
|
||||
//MemberPath = memberPath,
|
||||
TargetObj = targetObj,
|
||||
Op = ParseValueTypeOperator<double>(operatorStr),
|
||||
Value = value,
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0])
|
||||
};
|
||||
|
||||
}
|
||||
#endregion
|
||||
#region 解析类型 bool
|
||||
else if (type == typeof(bool))
|
||||
{
|
||||
return new MemberConditionResolver<bool>
|
||||
{
|
||||
//MemberPath = memberPath,
|
||||
TargetObj = targetObj,
|
||||
Op = (ValueTypeConditionResolver<bool>.Operator)ParseBoolOperator(operatorStr)
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
#region 解析类型 string
|
||||
else if (type == typeof(string))
|
||||
{
|
||||
return new MemberStringConditionResolver
|
||||
{
|
||||
MemberPath = memberPath,
|
||||
Op = ParseStringOperator(operatorStr),
|
||||
Value = valueStr
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
|
||||
throw new NotSupportedException($"Type {type} is not supported.");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 条件表达式解析
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="expression"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
/// <exception cref="NotSupportedException"></exception>
|
||||
private static SereinConditionResolver ParseSimpleExpression(object data, string expression)
|
||||
{
|
||||
if ("pass".Equals(expression.ToLower()))
|
||||
{
|
||||
return new PassConditionResolver
|
||||
{
|
||||
Op = PassConditionResolver.Operator.Pass,
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
if ("not pass".Equals(expression.ToLower()))
|
||||
{
|
||||
return new PassConditionResolver
|
||||
{
|
||||
Op = PassConditionResolver.Operator.NotPass,
|
||||
};
|
||||
}
|
||||
if ("!pass".Equals(expression.ToLower()))
|
||||
{
|
||||
return new PassConditionResolver
|
||||
{
|
||||
Op = PassConditionResolver.Operator.NotPass,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var parts = expression.Split(' ');
|
||||
|
||||
if (parts.Length < 2)
|
||||
throw new ArgumentException("无效的表达式格式。");
|
||||
|
||||
string operatorStr;
|
||||
string valueStr;
|
||||
Type type = null;
|
||||
// 尝试获取指定类型
|
||||
int typeStartIndex = expression.IndexOf('<');
|
||||
int typeEndIndex = expression.IndexOf('>');
|
||||
if (typeStartIndex + typeStartIndex == -2)
|
||||
{
|
||||
// 如果不需要转为指定类型
|
||||
operatorStr = parts[0];
|
||||
#if NET8_0_OR_GREATER
|
||||
valueStr = string.Join(' ', parts, 1, parts.Length - 1);
|
||||
|
||||
#elif NET462_OR_GREATER
|
||||
|
||||
valueStr = StringHelper.JoinStrings(parts, 1, parts.Length - 1, ' ');
|
||||
#endif
|
||||
|
||||
type = data.GetType();
|
||||
}
|
||||
else
|
||||
{//string typeStr = parts[0];
|
||||
string typeStr = expression.Substring(typeStartIndex + 1, typeEndIndex - typeStartIndex - 1)
|
||||
.Trim().ToLower(); // 手动置顶的类型
|
||||
parts = expression.Substring(typeEndIndex + 1).Trim().Split(' ');
|
||||
operatorStr = parts[0].ToLower(); // 操作类型
|
||||
valueStr = string.Join(" ", parts.Skip(1)); // 表达式值
|
||||
|
||||
|
||||
Type tempType;
|
||||
|
||||
switch (typeStr)
|
||||
{
|
||||
case "bool":
|
||||
tempType = typeof(bool);
|
||||
break;
|
||||
case "float":
|
||||
tempType = typeof(float);
|
||||
break;
|
||||
case "decimal":
|
||||
tempType = typeof(decimal);
|
||||
break;
|
||||
case "double":
|
||||
tempType = typeof(double);
|
||||
break;
|
||||
case "sbyte":
|
||||
tempType = typeof(sbyte);
|
||||
break;
|
||||
case "byte":
|
||||
tempType = typeof(byte);
|
||||
break;
|
||||
case "short":
|
||||
tempType = typeof(short);
|
||||
break;
|
||||
case "ushort":
|
||||
tempType = typeof(ushort);
|
||||
break;
|
||||
case "int":
|
||||
tempType = typeof(int);
|
||||
break;
|
||||
case "uint":
|
||||
tempType = typeof(uint);
|
||||
break;
|
||||
case "long":
|
||||
tempType = typeof(long);
|
||||
break;
|
||||
case "ulong":
|
||||
tempType = typeof(ulong);
|
||||
break;
|
||||
// 如果需要支持 nint 和 nuint
|
||||
// case "nint":
|
||||
// tempType = typeof(nint);
|
||||
// break;
|
||||
// case "nuint":
|
||||
// tempType = typeof(nuint);
|
||||
// break;
|
||||
case "string":
|
||||
tempType = typeof(string);
|
||||
break;
|
||||
default:
|
||||
tempType = Type.GetType(typeStr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
bool value = bool.Parse(valueStr);
|
||||
return new BoolConditionResolver
|
||||
{
|
||||
Op = ParseBoolOperator(operatorStr),
|
||||
Value = value,
|
||||
};
|
||||
}
|
||||
else if (type.IsValueType)
|
||||
{
|
||||
return GetValueResolver(type, valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (type == typeof(string))
|
||||
{
|
||||
return new StringConditionResolver
|
||||
{
|
||||
Op = ParseStringOperator(operatorStr),
|
||||
Value = valueStr
|
||||
};
|
||||
}
|
||||
|
||||
throw new NotSupportedException($"Type {type} is not supported.");
|
||||
}
|
||||
|
||||
public static SereinConditionResolver GetValueResolver(Type valueType, string valueStr, string operatorStr, string[] parts)// where T : struct, IComparable<T>
|
||||
{
|
||||
SereinConditionResolver resolver;
|
||||
|
||||
if (valueType == typeof(float))
|
||||
{
|
||||
resolver = GetValueResolver<float>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(decimal))
|
||||
{
|
||||
resolver = GetValueResolver<decimal>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(double))
|
||||
{
|
||||
resolver = GetValueResolver<double>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(sbyte))
|
||||
{
|
||||
resolver = GetValueResolver<sbyte>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(byte))
|
||||
{
|
||||
resolver = GetValueResolver<byte>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(short))
|
||||
{
|
||||
resolver = GetValueResolver<short>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(ushort))
|
||||
{
|
||||
resolver = GetValueResolver<ushort>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(int))
|
||||
{
|
||||
resolver = GetValueResolver<int>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(uint))
|
||||
{
|
||||
resolver = GetValueResolver<uint>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(long))
|
||||
{
|
||||
resolver = GetValueResolver<long>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(ulong))
|
||||
{
|
||||
resolver = GetValueResolver<ulong>(valueStr, operatorStr, parts);
|
||||
}
|
||||
#if NET8_0_OR_GREATER
|
||||
else if (valueType == typeof(nint))
|
||||
{
|
||||
resolver = GetValueResolver<nint>(valueStr, operatorStr, parts);
|
||||
}
|
||||
else if (valueType == typeof(nuint))
|
||||
{
|
||||
resolver = GetValueResolver<nuint>(valueStr, operatorStr, parts);
|
||||
}
|
||||
#endif
|
||||
else
|
||||
{
|
||||
throw new ArgumentException("非预期值类型");
|
||||
}
|
||||
|
||||
return resolver;
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static ValueTypeConditionResolver<T> GetValueResolver<T>(string valueStr, string operatorStr, string[] parts)
|
||||
where T :struct, IComparable<T>
|
||||
{
|
||||
var op = ParseValueTypeOperator<T>(operatorStr);
|
||||
if (op == ValueTypeConditionResolver<T>.Operator.InRange || op == ValueTypeConditionResolver<T>.Operator.OutOfRange)
|
||||
{
|
||||
var temp = valueStr.Split('-');
|
||||
var leftNum = string.Empty;
|
||||
var rightNum = string.Empty;
|
||||
if (temp.Length < 2 || temp.Length > 4)
|
||||
{
|
||||
throw new ArgumentException($"范围无效:{valueStr}。");
|
||||
}
|
||||
else if (temp.Length == 2)
|
||||
{
|
||||
leftNum = temp[0];
|
||||
rightNum = temp[1];
|
||||
}
|
||||
else if (temp.Length == 3)
|
||||
{
|
||||
if (string.IsNullOrEmpty(temp[0])
|
||||
&& !string.IsNullOrEmpty(temp[1])
|
||||
&& !string.IsNullOrEmpty(temp[2]))
|
||||
{
|
||||
leftNum = "-" + temp[1];
|
||||
rightNum = temp[2];
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"范围无效:{valueStr}。");
|
||||
}
|
||||
}
|
||||
else if (temp.Length == 4)
|
||||
{
|
||||
if (string.IsNullOrEmpty(temp[0])
|
||||
&& !string.IsNullOrEmpty(temp[1])
|
||||
&& string.IsNullOrEmpty(temp[2])
|
||||
&& !string.IsNullOrEmpty(temp[3]))
|
||||
{
|
||||
leftNum = "-" + temp[1];
|
||||
rightNum = temp[3];
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"范围无效:{valueStr}。");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
return new ValueTypeConditionResolver<T>
|
||||
{
|
||||
Op = op,
|
||||
RangeStart = leftNum.ToValueData<T>(),
|
||||
RangeEnd = rightNum.ToValueData<T>(),
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0]),
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
return new ValueTypeConditionResolver<T>
|
||||
{
|
||||
Op = op,
|
||||
Value = valueStr.ToValueData<T>(),
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0])
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
//public static T ValueParse<T>(object value) where T : struct, IComparable<T>
|
||||
//{
|
||||
// return (T)ValueParse(typeof(T), value);
|
||||
//}
|
||||
|
||||
//public static object ValueParse(Type type, object value)
|
||||
//{
|
||||
|
||||
// string? valueStr = value.ToString();
|
||||
// if (string.IsNullOrEmpty(valueStr))
|
||||
// {
|
||||
// throw new ArgumentException("value is null");
|
||||
// }
|
||||
// object result = type switch
|
||||
// {
|
||||
// Type t when t.IsEnum => Enum.Parse(type, valueStr),
|
||||
// Type t when t == typeof(bool) => bool.Parse(valueStr),
|
||||
// Type t when t == typeof(float) => float.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(decimal) => decimal.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(double) => double.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(sbyte) => sbyte.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(byte) => byte.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(short) => short.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(ushort) => ushort.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(int) => int.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(uint) => uint.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(long) => long.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(ulong) => ulong.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(nint) => nint.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// Type t when t == typeof(nuint) => nuint.Parse(valueStr, CultureInfo.InvariantCulture),
|
||||
// _ => throw new ArgumentException("非预期值类型")
|
||||
// };
|
||||
// return result;
|
||||
//}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 数值操作类型
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="operatorStr"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
private static ValueTypeConditionResolver<T>.Operator ParseValueTypeOperator<T>(string operatorStr) where T : struct, IComparable<T>
|
||||
{
|
||||
if (operatorStr == ">")
|
||||
{
|
||||
return ValueTypeConditionResolver<T>.Operator.GreaterThan;
|
||||
}
|
||||
else if (operatorStr == "<")
|
||||
{
|
||||
return ValueTypeConditionResolver<T>.Operator.LessThan;
|
||||
}
|
||||
else if (operatorStr == "==")
|
||||
{
|
||||
return ValueTypeConditionResolver<T>.Operator.Equal;
|
||||
}
|
||||
else if (operatorStr == ">=" || operatorStr == "≥")
|
||||
{
|
||||
return ValueTypeConditionResolver<T>.Operator.GreaterThanOrEqual;
|
||||
}
|
||||
else if (operatorStr == "<=" || operatorStr == "≤")
|
||||
{
|
||||
return ValueTypeConditionResolver<T>.Operator.LessThanOrEqual;
|
||||
}
|
||||
else if (operatorStr == "in")
|
||||
{
|
||||
return ValueTypeConditionResolver<T>.Operator.InRange;
|
||||
}
|
||||
else if (operatorStr == "!in")
|
||||
{
|
||||
return ValueTypeConditionResolver<T>.Operator.OutOfRange;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Invalid operator {operatorStr} for value type.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 布尔操作类型
|
||||
/// </summary>
|
||||
/// <param name="operatorStr"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
private static BoolConditionResolver.Operator ParseBoolOperator(string operatorStr)
|
||||
{
|
||||
if (operatorStr == "is" || operatorStr == "==" || operatorStr == "equals")
|
||||
{
|
||||
return BoolConditionResolver.Operator.Is;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Invalid operator {operatorStr} for bool type.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 字符串操作类型
|
||||
/// </summary>
|
||||
/// <param name="operatorStr"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
private static StringConditionResolver.Operator ParseStringOperator(string operatorStr)
|
||||
{
|
||||
operatorStr = operatorStr.ToLower();
|
||||
|
||||
if (operatorStr == "c" || operatorStr == "contains")
|
||||
{
|
||||
return StringConditionResolver.Operator.Contains;
|
||||
}
|
||||
else if (operatorStr == "nc" || operatorStr == "doesnotcontain")
|
||||
{
|
||||
return StringConditionResolver.Operator.DoesNotContain;
|
||||
}
|
||||
else if (operatorStr == "sw" || operatorStr == "startswith")
|
||||
{
|
||||
return StringConditionResolver.Operator.StartsWith;
|
||||
}
|
||||
else if (operatorStr == "ew" || operatorStr == "endswith")
|
||||
{
|
||||
return StringConditionResolver.Operator.EndsWith;
|
||||
}
|
||||
else if (operatorStr == "==" || operatorStr == "equals")
|
||||
{
|
||||
return StringConditionResolver.Operator.Equal;
|
||||
}
|
||||
else if (operatorStr == "!=" || operatorStr == "notequals")
|
||||
{
|
||||
return StringConditionResolver.Operator.NotEqual;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Invalid operator {operatorStr} for string type.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
12
Library/Utils/SereinExpression/SereinConditionResolver.cs
Normal file
12
Library/Utils/SereinExpression/SereinConditionResolver.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression
|
||||
{
|
||||
/// <summary>
|
||||
/// 条件解析抽象类
|
||||
/// </summary>
|
||||
public abstract class SereinConditionResolver
|
||||
{
|
||||
public abstract bool Evaluate(object obj);
|
||||
}
|
||||
}
|
||||
378
Library/Utils/SereinExpression/SerinExpressionEvaluator.cs
Normal file
378
Library/Utils/SereinExpression/SerinExpressionEvaluator.cs
Normal file
@@ -0,0 +1,378 @@
|
||||
using Serein.Library.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SereinExpression
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用表达式操作/获取 对象的值
|
||||
/// 获取值 @get .xx.xxx
|
||||
/// 设置值 @set .xx.xxx = [data]
|
||||
/// </summary>
|
||||
/// <param name="obj">操作的对象</param>
|
||||
/// <returns></returns>
|
||||
public class SerinArithmeticExpressionEvaluator<T> where T : struct, IComparable<T>
|
||||
{
|
||||
private static readonly DataTable table = new DataTable();
|
||||
|
||||
public static T Evaluate(string expression, T inputValue)
|
||||
{
|
||||
|
||||
// 替换占位符@为输入值
|
||||
expression = expression.Replace("@", inputValue.ToString());
|
||||
try
|
||||
{
|
||||
// 使用 DataTable.Compute 方法计算表达式
|
||||
var result = table.Compute(expression, string.Empty);
|
||||
return (T)result;
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new ArgumentException("Invalid arithmetic expression.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SerinExpressionEvaluator
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="expression">表达式</param>
|
||||
/// <param name="targetObJ">操作对象</param>
|
||||
/// <param name="isChange">是否改变了对象(Set语法)</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
/// <exception cref="NotSupportedException"></exception>
|
||||
public static object Evaluate(string expression, object targetObJ, out bool isChange)
|
||||
{
|
||||
//var parts = expression.Split([' '], 2);
|
||||
|
||||
var parts = expression.Split(new[] { ' ' }, 2, StringSplitOptions.None);
|
||||
if (parts.Length != 2)
|
||||
{
|
||||
throw new ArgumentException("Invalid expression format.");
|
||||
}
|
||||
|
||||
var operation = parts[0].ToLower();
|
||||
var operand = parts[1][0] == '.' ? parts[1].Substring(1) : parts[1];
|
||||
object result;
|
||||
if (operation == "@num")
|
||||
{
|
||||
result = ComputedNumber(targetObJ, operand);
|
||||
}
|
||||
else if (operation == "@call")
|
||||
{
|
||||
result = InvokeMethod(targetObJ, operand);
|
||||
}
|
||||
else if (operation == "@get")
|
||||
{
|
||||
result = GetMember(targetObJ, operand);
|
||||
}
|
||||
else if (operation == "@set")
|
||||
{
|
||||
result = SetMember(targetObJ, operand);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException($"Operation {operation} is not supported.");
|
||||
}
|
||||
|
||||
if(operation == "@set")
|
||||
{
|
||||
isChange = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
isChange = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
private static readonly char[] separator = new char[] { '(', ')' };
|
||||
private static readonly char[] separatorArray = new char[] { ',' };
|
||||
|
||||
/// <summary>
|
||||
/// 调用目标方法
|
||||
/// </summary>
|
||||
/// <param name="target">目标实例</param>
|
||||
/// <param name="methodCall">方法名称</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
private static object InvokeMethod(object target, string methodCall)
|
||||
{
|
||||
if (target is null) return null;
|
||||
var methodParts = methodCall.Split(separator, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (methodParts.Length != 2)
|
||||
{
|
||||
throw new ArgumentException("Invalid method call format.");
|
||||
}
|
||||
|
||||
var methodName = methodParts[0];
|
||||
var parameterList = methodParts[1];
|
||||
var parameters = parameterList.Split(separatorArray, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(p => p.Trim())
|
||||
.ToArray();
|
||||
|
||||
var method = target.GetType().GetMethod(methodName) ?? throw new ArgumentException($"Method {methodName} not found on target.");
|
||||
var parameterValues = method.GetParameters()
|
||||
.Select((p, index) => Convert.ChangeType(parameters[index], p.ParameterType))
|
||||
.ToArray();
|
||||
|
||||
|
||||
return method.Invoke(target, parameterValues);
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取值
|
||||
/// </summary>
|
||||
/// <param name="target">目标实例</param>
|
||||
/// <param name="memberPath">属性路径</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
private static object GetMember(object target, string memberPath)
|
||||
{
|
||||
if (target is null) return null;
|
||||
// 分割成员路径,按 '.' 处理多级访问
|
||||
var members = memberPath.Split('.');
|
||||
|
||||
foreach (var member in members)
|
||||
{
|
||||
// 检查成员是否包含数组索引,例如 "cars[0]"
|
||||
var arrayIndexStart = member.IndexOf('[');
|
||||
if (arrayIndexStart != -1)
|
||||
{
|
||||
// 解析数组/集合名与索引部分
|
||||
var arrayName = member.Substring(0, arrayIndexStart);
|
||||
var arrayIndexEnd = member.IndexOf(']');
|
||||
if (arrayIndexEnd == -1 || arrayIndexEnd <= arrayIndexStart + 1)
|
||||
{
|
||||
throw new ArgumentException($"Invalid array syntax for member {member}");
|
||||
}
|
||||
|
||||
// 提取数组索引
|
||||
var indexStr = member.Substring(arrayIndexStart + 1, arrayIndexEnd - arrayIndexStart - 1);
|
||||
if (!int.TryParse(indexStr, out int index))
|
||||
{
|
||||
throw new ArgumentException($"Invalid array index '{indexStr}' for member {member}");
|
||||
}
|
||||
|
||||
// 获取数组或集合对象
|
||||
var arrayProperty = target?.GetType().GetProperty(arrayName);
|
||||
if (arrayProperty is null)
|
||||
{
|
||||
var arrayField = target?.GetType().GetField(arrayName);
|
||||
if (arrayField is null)
|
||||
{
|
||||
throw new ArgumentException($"Member {arrayName} not found on target.");
|
||||
}
|
||||
else
|
||||
{
|
||||
target = arrayField.GetValue(target);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
target = arrayProperty.GetValue(target);
|
||||
}
|
||||
|
||||
// 访问数组或集合中的指定索引
|
||||
if (target is Array array)
|
||||
{
|
||||
if (index < 0 || index >= array.Length)
|
||||
{
|
||||
throw new ArgumentException($"Index {index} out of bounds for array {arrayName}");
|
||||
}
|
||||
target = array.GetValue(index);
|
||||
}
|
||||
else if (target is IList<object> list)
|
||||
{
|
||||
if (index < 0 || index >= list.Count)
|
||||
{
|
||||
throw new ArgumentException($"Index {index} out of bounds for list {arrayName}");
|
||||
}
|
||||
target = list[index];
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Member {arrayName} is not an array or list.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 处理非数组情况的属性或字段
|
||||
var property = target?.GetType().GetProperty(member);
|
||||
if (property is null)
|
||||
{
|
||||
var field = target?.GetType().GetField(member);
|
||||
if (field is null)
|
||||
{
|
||||
throw new ArgumentException($"Member {member} not found on target.");
|
||||
}
|
||||
else
|
||||
{
|
||||
target = field.GetValue(target);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
target = property.GetValue(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置目标的值
|
||||
/// </summary>
|
||||
/// <param name="target">目标实例</param>
|
||||
/// <param name="assignment">属性路径 </param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
private static object SetMember(object target, string assignment)
|
||||
{
|
||||
var parts = assignment.Split(new[] { '=' }, 2);
|
||||
if (parts.Length != 2)
|
||||
{
|
||||
throw new ArgumentException("Invalid assignment format.");
|
||||
}
|
||||
|
||||
var memberPath = parts[0].Trim();
|
||||
var value = parts[1].Trim();
|
||||
|
||||
var members = memberPath.Split('.');
|
||||
for (int i = 0; i < members.Length - 1; i++)
|
||||
{
|
||||
var member = members[i];
|
||||
|
||||
// 检查是否包含数组索引
|
||||
var arrayIndexStart = member.IndexOf('[');
|
||||
if (arrayIndexStart != -1)
|
||||
{
|
||||
// 解析数组名和索引
|
||||
var arrayName = member.Substring(0, arrayIndexStart);
|
||||
var arrayIndexEnd = member.IndexOf(']');
|
||||
if (arrayIndexEnd == -1 || arrayIndexEnd <= arrayIndexStart + 1)
|
||||
{
|
||||
throw new ArgumentException($"Invalid array syntax for member {member}");
|
||||
}
|
||||
|
||||
var indexStr = member.Substring(arrayIndexStart + 1, arrayIndexEnd - arrayIndexStart - 1);
|
||||
if (!int.TryParse(indexStr, out int index))
|
||||
{
|
||||
throw new ArgumentException($"Invalid array index '{indexStr}' for member {member}");
|
||||
}
|
||||
|
||||
// 获取数组或集合
|
||||
var arrayProperty = target?.GetType().GetProperty(arrayName);
|
||||
if (arrayProperty is null)
|
||||
{
|
||||
var arrayField = target?.GetType().GetField(arrayName);
|
||||
if (arrayField is null)
|
||||
{
|
||||
throw new ArgumentException($"Member {arrayName} not found on target.");
|
||||
}
|
||||
else
|
||||
{
|
||||
target = arrayField.GetValue(target);
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
target = arrayProperty.GetValue(target);
|
||||
}
|
||||
|
||||
// 获取目标数组或集合中的指定元素
|
||||
if (target is Array array)
|
||||
{
|
||||
if (index < 0 || index >= array.Length)
|
||||
{
|
||||
throw new ArgumentException($"Index {index} out of bounds for array {arrayName}");
|
||||
}
|
||||
target = array.GetValue(index);
|
||||
}
|
||||
else if (target is IList<object> list)
|
||||
{
|
||||
if (index < 0 || index >= list.Count)
|
||||
{
|
||||
throw new ArgumentException($"Index {index} out of bounds for list {arrayName}");
|
||||
}
|
||||
target = list[index];
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Member {arrayName} is not an array or list.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// 处理非数组情况的属性或字段
|
||||
var property = target?.GetType().GetProperty(member);
|
||||
if (property is null)
|
||||
{
|
||||
var field = target?.GetType().GetField(member);
|
||||
if (field is null)
|
||||
{
|
||||
throw new ArgumentException($"Member {member} not found on target.");
|
||||
}
|
||||
else
|
||||
{
|
||||
target = field.GetValue(target);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
target = property.GetValue(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置值
|
||||
var lastMember = members.Last();
|
||||
|
||||
var lastProperty = target?.GetType().GetProperty(lastMember);
|
||||
if (lastProperty is null)
|
||||
{
|
||||
var lastField = target?.GetType().GetField(lastMember);
|
||||
if (lastField is null)
|
||||
{
|
||||
throw new ArgumentException($"Member {lastMember} not found on target.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var convertedValue = Convert.ChangeType(value, lastField.FieldType);
|
||||
lastField.SetValue(target, convertedValue);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var convertedValue = Convert.ChangeType(value, lastProperty.PropertyType);
|
||||
lastProperty.SetValue(target, convertedValue);
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
/// <summary>
|
||||
/// 计算数学简单表达式
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expression"></param>
|
||||
/// <returns></returns>
|
||||
private static decimal ComputedNumber(object value, string expression)
|
||||
{
|
||||
return ComputedNumber<decimal>(value, expression);
|
||||
}
|
||||
|
||||
private static T ComputedNumber<T>(object value, string expression) where T : struct, IComparable<T>
|
||||
{
|
||||
T result = value.ToConvert<T>();
|
||||
return SerinArithmeticExpressionEvaluator<T>.Evaluate(expression, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,8 +87,7 @@ namespace Serein.Library.Utils
|
||||
/// <summary>
|
||||
/// 用于临时实例的创建,不登记到IOC容器中,依赖项注入失败时也不记录。
|
||||
/// </summary>
|
||||
/// <param name="controllerType"></param>
|
||||
/// <param name="parameters"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public object Instantiate(Type type)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user