mirror of
https://gitee.com/langsisi_admin/serein-flow
synced 2026-03-20 08:16:34 +08:00
重写了节点的view、viewmodel关系,实现了对画布元素的选取功能,重构了底层依赖,添加了对net .Framework4.6.1以上的Framework类库支持
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
using Serein.Library.IOC;
|
||||
|
||||
using Serein.NodeFlow.Model;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
@@ -19,36 +19,97 @@ namespace Serein.NodeFlow
|
||||
// Cancel,
|
||||
// Error,
|
||||
//}
|
||||
|
||||
//public class FlipflopContext
|
||||
//{
|
||||
// public FlowStateType State { get; set; }
|
||||
// public object? Data { get; set; }
|
||||
// public FlipflopContext(FlowStateType ffState, object? data = null)
|
||||
// {
|
||||
// State = ffState;
|
||||
// Data = data;
|
||||
// }
|
||||
//}
|
||||
|
||||
public static class FlipflopFunc
|
||||
{
|
||||
/// <summary>
|
||||
/// 传入触发器方法的返回类型,尝试获取Task[Flipflop[]] 中的泛型类型
|
||||
/// </summary>
|
||||
//public static Type GetFlipflopInnerType(Type type)
|
||||
//{
|
||||
// // 检查是否为泛型类型且为 Task<>
|
||||
// if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Task<>))
|
||||
// {
|
||||
// // 获取 Task<> 的泛型参数类型,即 Flipflop<>
|
||||
// var innerType = type.GetGenericArguments()[0];
|
||||
|
||||
// // 检查泛型参数是否为 Flipflop<>
|
||||
// if (innerType.IsGenericType && innerType.GetGenericTypeDefinition() == typeof(FlipflopContext<>))
|
||||
// {
|
||||
// // 获取 Flipflop<> 的泛型参数类型,即 T
|
||||
// var flipflopInnerType = innerType.GetGenericArguments()[0];
|
||||
|
||||
// // 返回 Flipflop<> 中的具体类型
|
||||
// return flipflopInnerType;
|
||||
// }
|
||||
// }
|
||||
// // 如果不符合条件,返回 null
|
||||
// return null;
|
||||
//}
|
||||
|
||||
public static bool IsTaskOfFlipflop(Type type)
|
||||
{
|
||||
// 检查是否为泛型类型且为 Task<>
|
||||
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Task<>))
|
||||
{
|
||||
// 获取 Task<> 的泛型参数类型
|
||||
var innerType = type.GetGenericArguments()[0];
|
||||
|
||||
// 检查泛型参数是否为 Flipflop<>
|
||||
if (innerType == typeof(FlipflopContext))
|
||||
//if (innerType.IsGenericType && innerType.GetGenericTypeDefinition() == typeof(FlipflopContext<>))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 触发器上下文
|
||||
/// </summary>
|
||||
public class FlipflopContext
|
||||
public class FlipflopContext//<TResult>
|
||||
{
|
||||
public FlowStateType State { get; set; }
|
||||
public LibraryCore.NodeFlow.FlowStateType State { get; set; }
|
||||
//public TResult? Data { get; set; }
|
||||
public object? Data { get; set; }
|
||||
/*public FlipflopContext()
|
||||
public FlipflopContext(FlowStateType ffState)
|
||||
{
|
||||
State = FfState.Cancel;
|
||||
}*/
|
||||
public FlipflopContext(FlowStateType ffState, object? data = null)
|
||||
State = ffState;
|
||||
}
|
||||
public FlipflopContext(FlowStateType ffState, object data)
|
||||
{
|
||||
State = ffState;
|
||||
Data = data;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态流程上下文
|
||||
/// </summary>
|
||||
|
||||
public class DynamicContext(IServiceContainer serviceContainer)
|
||||
public class DynamicContext(ISereinIoc serviceContainer)
|
||||
|
||||
{
|
||||
|
||||
private readonly string contextGuid = "";//System.Guid.NewGuid().ToString();
|
||||
|
||||
public IServiceContainer ServiceContainer { get; } = serviceContainer;
|
||||
public ISereinIoc ServiceContainer { get; } = serviceContainer;
|
||||
private List<Type> InitServices { get; set; } = [];
|
||||
|
||||
// private ConcurrentDictionary<string, object?> ContextData { get; set; } = [];
|
||||
@@ -152,7 +213,7 @@ namespace Serein.NodeFlow
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
NodeRunCts.Token.ThrowIfCancellationRequested();
|
||||
await time;
|
||||
await Task.Delay(time);
|
||||
action.Invoke();
|
||||
}
|
||||
});
|
||||
|
||||
38
NodeFlow/DynamicNodeFrameworkType.cs
Normal file
38
NodeFlow/DynamicNodeFrameworkType.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow
|
||||
{
|
||||
//public enum DynamicNodeType
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 初始化
|
||||
// /// </summary>
|
||||
// Init,
|
||||
// /// <summary>
|
||||
// /// 开始载入
|
||||
// /// </summary>
|
||||
// Loading,
|
||||
// /// <summary>
|
||||
// /// 结束
|
||||
// /// </summary>
|
||||
// Exit,
|
||||
|
||||
// /// <summary>
|
||||
// /// 触发器
|
||||
// /// </summary>
|
||||
// Flipflop,
|
||||
// /// <summary>
|
||||
// /// 条件节点
|
||||
// /// </summary>
|
||||
// Condition,
|
||||
// /// <summary>
|
||||
// /// 动作节点
|
||||
// /// </summary>
|
||||
// Action,
|
||||
//}
|
||||
|
||||
}
|
||||
24
NodeFlow/FlowStateType.cs
Normal file
24
NodeFlow/FlowStateType.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow
|
||||
{
|
||||
//public enum FlowStateType
|
||||
//{
|
||||
// /// <summary>
|
||||
// /// 成功(方法成功执行)
|
||||
// /// </summary>
|
||||
// Succeed,
|
||||
// /// <summary>
|
||||
// /// 失败(方法没有成功执行,不过执行时没有发生非预期的错误)
|
||||
// /// </summary>
|
||||
// Fail,
|
||||
// /// <summary>
|
||||
// /// 异常(节点没有成功执行,执行时发生非预期的错误)
|
||||
// /// </summary>
|
||||
// Error,
|
||||
//}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
namespace Serein.NodeFlow
|
||||
using Serein.Library.Enums;
|
||||
|
||||
namespace Serein.NodeFlow
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 显式参数
|
||||
/// </summary>
|
||||
@@ -63,6 +67,10 @@
|
||||
|
||||
public class MethodDetails
|
||||
{
|
||||
/// <summary>
|
||||
/// 拷贝
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public MethodDetails Clone()
|
||||
{
|
||||
return new MethodDetails
|
||||
@@ -76,7 +84,7 @@
|
||||
ReturnType = ReturnType,
|
||||
MethodName = MethodName,
|
||||
MethodLockName = MethodLockName,
|
||||
|
||||
IsNetFramework = IsNetFramework,
|
||||
ExplicitDatas = ExplicitDatas.Select(it => it.Clone()).ToArray(),
|
||||
};
|
||||
}
|
||||
@@ -114,7 +122,7 @@
|
||||
/// <summary>
|
||||
/// 节点类型
|
||||
/// </summary>
|
||||
public DynamicNodeType MethodDynamicType { get; set; }
|
||||
public NodeType MethodDynamicType { get; set; }
|
||||
/// <summary>
|
||||
/// 锁名称
|
||||
/// </summary>
|
||||
@@ -135,98 +143,97 @@
|
||||
|
||||
public ExplicitData[] ExplicitDatas { get; set; }
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 出参类型
|
||||
/// </summary>
|
||||
|
||||
public Type ReturnType { get; set; }
|
||||
|
||||
public bool IsNetFramework { get; set; }
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public bool IsCanConnect(Type returnType)
|
||||
{
|
||||
if (ExplicitDatas.Length == 0)
|
||||
{
|
||||
// 目标不需要传参,可以舍弃结果?
|
||||
return true;
|
||||
}
|
||||
var types = ExplicitDatas.Select(it => it.DataType).ToArray();
|
||||
// 检查返回类型是否是元组类型
|
||||
if (returnType.IsGenericType && IsValueTuple(returnType))
|
||||
{
|
||||
//public bool IsCanConnect(Type returnType)
|
||||
//{
|
||||
// if (ExplicitDatas.Length == 0)
|
||||
// {
|
||||
// // 目标不需要传参,可以舍弃结果?
|
||||
// return true;
|
||||
// }
|
||||
// var types = ExplicitDatas.Select(it => it.DataType).ToArray();
|
||||
// // 检查返回类型是否是元组类型
|
||||
// if (returnType.IsGenericType && IsValueTuple(returnType))
|
||||
// {
|
||||
|
||||
return CompareGenericArguments(returnType, types);
|
||||
}
|
||||
else
|
||||
{
|
||||
int index = 0;
|
||||
if (types[index] == typeof(DynamicContext))
|
||||
{
|
||||
index++;
|
||||
if (types.Length == 1)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// 被连接节点检查自己需要的参数类型,与发起连接的节点比较返回值类型
|
||||
if (returnType == types[index])
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// return CompareGenericArguments(returnType, types);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// int index = 0;
|
||||
// if (types[index] == typeof(DynamicContext))
|
||||
// {
|
||||
// index++;
|
||||
// if (types.Length == 1)
|
||||
// {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
// // 被连接节点检查自己需要的参数类型,与发起连接的节点比较返回值类型
|
||||
// if (returnType == types[index])
|
||||
// {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
// return false;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 检查元组类型
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
private bool IsValueTuple(Type type)
|
||||
{
|
||||
if (!type.IsGenericType) return false;
|
||||
///// <summary>
|
||||
///// 检查元组类型
|
||||
///// </summary>
|
||||
///// <param name="type"></param>
|
||||
///// <returns></returns>
|
||||
//private bool IsValueTuple(Type type)
|
||||
//{
|
||||
// if (!type.IsGenericType) return false;
|
||||
|
||||
var genericTypeDef = type.GetGenericTypeDefinition();
|
||||
return genericTypeDef == typeof(ValueTuple<>) ||
|
||||
genericTypeDef == typeof(ValueTuple<,>) ||
|
||||
genericTypeDef == typeof(ValueTuple<,,>) ||
|
||||
genericTypeDef == typeof(ValueTuple<,,,>) ||
|
||||
genericTypeDef == typeof(ValueTuple<,,,,>) ||
|
||||
genericTypeDef == typeof(ValueTuple<,,,,,>) ||
|
||||
genericTypeDef == typeof(ValueTuple<,,,,,,>) ||
|
||||
genericTypeDef == typeof(ValueTuple<,,,,,,,>);
|
||||
}
|
||||
// var genericTypeDef = type.GetGenericTypeDefinition();
|
||||
// return genericTypeDef == typeof(ValueTuple<>) ||
|
||||
// genericTypeDef == typeof(ValueTuple<,>) ||
|
||||
// genericTypeDef == typeof(ValueTuple<,,>) ||
|
||||
// genericTypeDef == typeof(ValueTuple<,,,>) ||
|
||||
// genericTypeDef == typeof(ValueTuple<,,,,>) ||
|
||||
// genericTypeDef == typeof(ValueTuple<,,,,,>) ||
|
||||
// genericTypeDef == typeof(ValueTuple<,,,,,,>) ||
|
||||
// genericTypeDef == typeof(ValueTuple<,,,,,,,>);
|
||||
//}
|
||||
|
||||
private bool CompareGenericArguments(Type returnType, Type[] parameterTypes)
|
||||
{
|
||||
var genericArguments = returnType.GetGenericArguments();
|
||||
var length = parameterTypes.Length;
|
||||
//private bool CompareGenericArguments(Type returnType, Type[] parameterTypes)
|
||||
//{
|
||||
// var genericArguments = returnType.GetGenericArguments();
|
||||
// var length = parameterTypes.Length;
|
||||
|
||||
for (int i = 0; i < genericArguments.Length; i++)
|
||||
{
|
||||
if (i >= length) return false;
|
||||
// for (int i = 0; i < genericArguments.Length; i++)
|
||||
// {
|
||||
// if (i >= length) return false;
|
||||
|
||||
if (IsValueTuple(genericArguments[i]))
|
||||
{
|
||||
// 如果当前参数也是 ValueTuple,递归检查嵌套的泛型参数
|
||||
if (!CompareGenericArguments(genericArguments[i], parameterTypes.Skip(i).ToArray()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (genericArguments[i] != parameterTypes[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// if (IsValueTuple(genericArguments[i]))
|
||||
// {
|
||||
// // 如果当前参数也是 ValueTuple,递归检查嵌套的泛型参数
|
||||
// if (!CompareGenericArguments(genericArguments[i], parameterTypes.Skip(i).ToArray()))
|
||||
// {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
// else if (genericArguments[i] != parameterTypes[i])
|
||||
// {
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
|
||||
return true;
|
||||
}
|
||||
// return true;
|
||||
//}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
namespace Serein.NodeFlow.Model
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Enums;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
|
||||
namespace Serein.NodeFlow.Model
|
||||
{
|
||||
/// <summary>
|
||||
/// 组合条件节点(用于条件区域)
|
||||
@@ -19,7 +23,7 @@
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public override object? Execute(DynamicContext context)
|
||||
public override object? Execute(IDynamicContext context)
|
||||
{
|
||||
// bool allTrue = ConditionNodes.All(condition => Judge(context,condition.MethodDetails));
|
||||
// bool IsAllTrue = true; // 初始化为 true
|
||||
@@ -50,7 +54,7 @@
|
||||
// }
|
||||
//}
|
||||
}
|
||||
private FlowStateType Judge(DynamicContext context, SingleConditionNode node)
|
||||
private FlowStateType Judge(IDynamicContext context, SingleConditionNode node)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using Newtonsoft.Json;
|
||||
using Serein.NodeFlow;
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Enums;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
using Serein.NodeFlow.Tool;
|
||||
using Serein.NodeFlow.Tool.SerinExpression;
|
||||
|
||||
namespace Serein.NodeFlow.Model
|
||||
{
|
||||
@@ -25,21 +28,6 @@ namespace Serein.NodeFlow.Model
|
||||
Upstream,
|
||||
}
|
||||
|
||||
public enum FlowStateType
|
||||
{
|
||||
/// <summary>
|
||||
/// 成功(方法成功执行)
|
||||
/// </summary>
|
||||
Succeed,
|
||||
/// <summary>
|
||||
/// 失败(方法没有成功执行,不过执行时没有发生非预期的错误)
|
||||
/// </summary>
|
||||
Fail,
|
||||
/// <summary>
|
||||
/// 异常(节点没有
|
||||
/// </summary>
|
||||
Error,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
|
||||
@@ -103,7 +91,7 @@ namespace Serein.NodeFlow.Model
|
||||
/// </summary>
|
||||
/// <param name="context">流程上下文</param>
|
||||
/// <returns>节点传回数据对象</returns>
|
||||
public virtual object? Execute(DynamicContext context)
|
||||
public virtual object? Execute(IDynamicContext context)
|
||||
{
|
||||
MethodDetails md = MethodDetails;
|
||||
object? result = null;
|
||||
@@ -155,7 +143,7 @@ namespace Serein.NodeFlow.Model
|
||||
/// <param name="context"></param>
|
||||
/// <returns>节点传回数据对象</returns>
|
||||
/// <exception cref="Exception"></exception>
|
||||
public virtual async Task<object?> ExecuteAsync(DynamicContext context)
|
||||
public virtual async Task<object?> ExecuteAsync(IDynamicContext context)
|
||||
{
|
||||
MethodDetails md = MethodDetails;
|
||||
object? result = null;
|
||||
@@ -165,18 +153,18 @@ namespace Serein.NodeFlow.Model
|
||||
return result;
|
||||
}
|
||||
|
||||
FlipflopContext flipflopContext = null;
|
||||
IFlipflopContext flipflopContext = null;
|
||||
try
|
||||
{
|
||||
// 调用委托并获取结果
|
||||
if (md.ExplicitDatas.Length == 0)
|
||||
{
|
||||
flipflopContext = await ((Func<object, Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
|
||||
flipflopContext = await ((Func<object, Task<IFlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
|
||||
}
|
||||
else
|
||||
{
|
||||
object?[]? parameters = GetParameters(context, MethodDetails);
|
||||
flipflopContext = await ((Func<object, object[], Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
|
||||
flipflopContext = await ((Func<object, object[], Task<IFlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
|
||||
}
|
||||
|
||||
if (flipflopContext != null)
|
||||
@@ -186,6 +174,10 @@ namespace Serein.NodeFlow.Model
|
||||
{
|
||||
result = flipflopContext.Data;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -202,9 +194,9 @@ namespace Serein.NodeFlow.Model
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
public async Task StartExecution(DynamicContext context)
|
||||
public async Task StartExecution(IDynamicContext context)
|
||||
{
|
||||
var cts = context.ServiceContainer.GetOrInstantiate<CancellationTokenSource>();
|
||||
var cts = context.SereinIoc.GetOrInstantiate<CancellationTokenSource>();
|
||||
|
||||
Stack<NodeBase> stack = [];
|
||||
stack.Push(this);
|
||||
@@ -217,7 +209,7 @@ namespace Serein.NodeFlow.Model
|
||||
// 设置方法执行的对象
|
||||
if (currentNode.MethodDetails != null)
|
||||
{
|
||||
currentNode.MethodDetails.ActingInstance ??= context.ServiceContainer.GetOrInstantiate(MethodDetails.ActingInstanceType);
|
||||
currentNode.MethodDetails.ActingInstance ??= context.SereinIoc.GetOrInstantiate(MethodDetails.ActingInstanceType);
|
||||
}
|
||||
|
||||
// 获取上游分支,首先执行一次
|
||||
@@ -228,7 +220,7 @@ namespace Serein.NodeFlow.Model
|
||||
await upstreamNodes[i].StartExecution(context);
|
||||
}
|
||||
|
||||
if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == DynamicNodeType.Flipflop)
|
||||
if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == NodeType.Flipflop)
|
||||
{
|
||||
// 触发器节点
|
||||
currentNode.FlowData = await currentNode.ExecuteAsync(context);
|
||||
@@ -259,7 +251,7 @@ namespace Serein.NodeFlow.Model
|
||||
/// <summary>
|
||||
/// 获取对应的参数数组
|
||||
/// </summary>
|
||||
public object[]? GetParameters(DynamicContext context, MethodDetails md)
|
||||
public object[]? GetParameters(IDynamicContext context, MethodDetails md)
|
||||
{
|
||||
// 用正确的大小初始化参数数组
|
||||
var types = md.ExplicitDatas.Select(it => it.DataType).ToArray();
|
||||
@@ -278,7 +270,7 @@ namespace Serein.NodeFlow.Model
|
||||
|
||||
var f1 = PreviousNode?.FlowData?.GetType();
|
||||
var f2 = mdEd.DataType;
|
||||
if (type == typeof(DynamicContext))
|
||||
if (type == typeof(IDynamicContext))
|
||||
{
|
||||
parameters[i] = context;
|
||||
}
|
||||
@@ -292,37 +284,79 @@ namespace Serein.NodeFlow.Model
|
||||
}
|
||||
else if (mdEd.IsExplicitData) // 显式参数
|
||||
{
|
||||
if (mdEd.DataType.IsEnum)
|
||||
// 判断是否使用表达式解析
|
||||
if (mdEd.DataValue[0] == '@')
|
||||
{
|
||||
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
|
||||
parameters[i] = enumValue;
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(string))
|
||||
{
|
||||
parameters[i] = mdEd.DataValue;
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(bool))
|
||||
{
|
||||
parameters[i] = bool.Parse(mdEd.DataValue);
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(int))
|
||||
{
|
||||
parameters[i] = int.Parse(mdEd.DataValue);
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(double))
|
||||
{
|
||||
parameters[i] = double.Parse(mdEd.DataValue);
|
||||
var expResult = SerinExpressionEvaluator.Evaluate(mdEd.DataValue, PreviousNode?.FlowData, out bool isChange);
|
||||
|
||||
|
||||
if (mdEd.DataType.IsEnum)
|
||||
{
|
||||
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
|
||||
parameters[i] = enumValue;
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(string))
|
||||
{
|
||||
parameters[i] = Convert.ChangeType(expResult, typeof(string));
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(bool))
|
||||
{
|
||||
parameters[i] = Convert.ChangeType(expResult, typeof(bool));
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(int))
|
||||
{
|
||||
parameters[i] = Convert.ChangeType(expResult, typeof(int));
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(double))
|
||||
{
|
||||
parameters[i] = Convert.ChangeType(expResult, typeof(double));
|
||||
}
|
||||
else
|
||||
{
|
||||
parameters[i] = expResult;
|
||||
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
parameters[i] = "";
|
||||
if (mdEd.DataType.IsEnum)
|
||||
{
|
||||
var enumValue = Enum.Parse(mdEd.DataType, mdEd.DataValue);
|
||||
parameters[i] = enumValue;
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(string))
|
||||
{
|
||||
parameters[i] = mdEd.DataValue;
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(bool))
|
||||
{
|
||||
parameters[i] = bool.Parse(mdEd.DataValue);
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(int))
|
||||
{
|
||||
parameters[i] = int.Parse(mdEd.DataValue);
|
||||
}
|
||||
else if (mdEd.ExplicitType == typeof(double))
|
||||
{
|
||||
parameters[i] = double.Parse(mdEd.DataValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
parameters[i] = "";
|
||||
|
||||
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
|
||||
//parameters[i] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
else if (f1 != null && f2 != null && f2.IsAssignableFrom(f1) || f2.FullName.Equals(f1.FullName))
|
||||
else if (f1 != null && f2 != null)
|
||||
{
|
||||
parameters[i] = PreviousNode?.FlowData;
|
||||
if(f2.IsAssignableFrom(f1) || f2.FullName.Equals(f1.FullName))
|
||||
{
|
||||
parameters[i] = PreviousNode?.FlowData;
|
||||
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
|
||||
using Serein.Library.SerinExpression;
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Enums;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
using Serein.NodeFlow.Tool.SerinExpression;
|
||||
|
||||
namespace Serein.NodeFlow.Model
|
||||
{
|
||||
@@ -24,7 +27,7 @@ namespace Serein.NodeFlow.Model
|
||||
public string Expression { get; set; }
|
||||
|
||||
|
||||
public override object? Execute(DynamicContext context)
|
||||
public override object? Execute(IDynamicContext context)
|
||||
{
|
||||
// 接收上一节点参数or自定义参数内容
|
||||
object? result;
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
using Serein.Library.SerinExpression;
|
||||
using Serein.NodeFlow;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Enums;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
using Serein.NodeFlow.Tool.SerinExpression;
|
||||
|
||||
namespace Serein.NodeFlow.Model
|
||||
{
|
||||
@@ -19,7 +16,7 @@ namespace Serein.NodeFlow.Model
|
||||
public string Expression { get; set; }
|
||||
|
||||
|
||||
public override object? Execute(DynamicContext context)
|
||||
public override object? Execute(IDynamicContext context)
|
||||
{
|
||||
var data = PreviousNode?.FlowData;
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
using Serein.NodeFlow;
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
|
||||
namespace Serein.NodeFlow.Model
|
||||
{
|
||||
|
||||
public class SingleFlipflopNode : NodeBase
|
||||
{
|
||||
public override object Execute(DynamicContext context)
|
||||
public override object Execute(IDynamicContext context)
|
||||
{
|
||||
throw new NotImplementedException("无法以非await/async的形式调用触发器");
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
using Serein.Library.Http;
|
||||
using Serein.Library.IOC;
|
||||
using Serein.NodeFlow;
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Enums;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
using Serein.NodeFlow.Model;
|
||||
using Serein.NodeFlow.Tool;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Serein.NodeFlow
|
||||
{
|
||||
@@ -14,16 +13,16 @@ namespace Serein.NodeFlow
|
||||
}
|
||||
|
||||
|
||||
public class NodeFlowStarter(IServiceContainer serviceContainer, List<MethodDetails> methodDetails)
|
||||
public class NodeFlowStarter(ISereinIoc serviceContainer, List<MethodDetails> methodDetails)
|
||||
|
||||
{
|
||||
private readonly IServiceContainer ServiceContainer = serviceContainer;
|
||||
private readonly ISereinIoc ServiceContainer = serviceContainer;
|
||||
private readonly List<MethodDetails> methodDetails = methodDetails;
|
||||
|
||||
private Action ExitAction = null;
|
||||
|
||||
|
||||
private DynamicContext context = null;
|
||||
private IDynamicContext context = null;
|
||||
|
||||
|
||||
public NodeRunTcs MainCts;
|
||||
@@ -42,19 +41,26 @@ namespace Serein.NodeFlow
|
||||
{
|
||||
var startNode = nodes.FirstOrDefault(p => p.IsStart);
|
||||
if (startNode == null) { return; }
|
||||
context = new(ServiceContainer);
|
||||
if (false)
|
||||
{
|
||||
context = new Serein.Library.Core.NodeFlow.DynamicContext(ServiceContainer);
|
||||
}
|
||||
else
|
||||
{
|
||||
context = new Serein.Library.Framework.NodeFlow.DynamicContext(ServiceContainer);
|
||||
}
|
||||
|
||||
MainCts = ServiceContainer.CreateServiceInstance<NodeRunTcs>();
|
||||
|
||||
var initMethods = methodDetails.Where(it => it.MethodDynamicType == DynamicNodeType.Init).ToList();
|
||||
var loadingMethods = methodDetails.Where(it => it.MethodDynamicType == DynamicNodeType.Loading).ToList();
|
||||
var exitMethods = methodDetails.Where(it => it.MethodDynamicType == DynamicNodeType.Exit).ToList();
|
||||
var initMethods = methodDetails.Where(it => it.MethodDynamicType == NodeType.Init).ToList();
|
||||
var loadingMethods = methodDetails.Where(it => it.MethodDynamicType == NodeType.Loading).ToList();
|
||||
var exitMethods = methodDetails.Where(it => it.MethodDynamicType == NodeType.Exit).ToList();
|
||||
ExitAction = () =>
|
||||
{
|
||||
ServiceContainer.Run<WebServer>((web) =>
|
||||
{
|
||||
web?.Stop();
|
||||
});
|
||||
//ServiceContainer.Run<WebServer>((web) =>
|
||||
//{
|
||||
// web?.Stop();
|
||||
//});
|
||||
foreach (MethodDetails? md in exitMethods)
|
||||
{
|
||||
object?[]? args = [context];
|
||||
@@ -77,7 +83,7 @@ namespace Serein.NodeFlow
|
||||
object?[]? data = [md.ActingInstance, args];
|
||||
md.MethodDelegate.DynamicInvoke(data);
|
||||
}
|
||||
context.Biuld();
|
||||
context.SereinIoc.Build();
|
||||
|
||||
foreach (var md in loadingMethods) // 加载
|
||||
{
|
||||
@@ -87,7 +93,7 @@ namespace Serein.NodeFlow
|
||||
md.MethodDelegate.DynamicInvoke(data);
|
||||
}
|
||||
|
||||
var flipflopNodes = nodes.Where(it => it.MethodDetails?.MethodDynamicType == DynamicNodeType.Flipflop
|
||||
var flipflopNodes = nodes.Where(it => it.MethodDetails?.MethodDynamicType == NodeType.Flipflop
|
||||
&& it.PreviousNodes.Count == 0
|
||||
&& it.IsStart != true).ToArray();
|
||||
|
||||
@@ -126,15 +132,17 @@ namespace Serein.NodeFlow
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
var func = md.ExplicitDatas.Length == 0 ? (Func<object, object, Task<FlipflopContext>>)del : (Func<object, object[], Task<FlipflopContext>>)del;
|
||||
//var func = md.ExplicitDatas.Length == 0 ? (Func<object, object, Task<FlipflopContext<dynamic>>>)del : (Func<object, object[], Task<FlipflopContext<dynamic>>>)del;
|
||||
var func = md.ExplicitDatas.Length == 0 ? (Func<object, object, Task<IFlipflopContext>>)del : (Func<object, object[], Task<IFlipflopContext>>)del;
|
||||
|
||||
while (!MainCts.IsCancellationRequested) // 循环中直到栈为空才会退出
|
||||
{
|
||||
object?[]? parameters = singleFlipFlopNode.GetParameters(context, md);
|
||||
// 调用委托并获取结果
|
||||
|
||||
FlipflopContext flipflopContext = await func.Invoke(md.ActingInstance, parameters);
|
||||
IFlipflopContext flipflopContext = await func.Invoke(md.ActingInstance, parameters);
|
||||
|
||||
if (flipflopContext == null)
|
||||
{
|
||||
|
||||
36
NodeFlow/Serein - Backup.NodeFlow.csproj
Normal file
36
NodeFlow/Serein - Backup.NodeFlow.csproj
Normal file
@@ -0,0 +1,36 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>D:\Project\C#\DynamicControl\SereinFlow\.Output</BaseOutputPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="bin\**" />
|
||||
<Compile Remove="SerinExpression\**" />
|
||||
<EmbeddedResource Remove="bin\**" />
|
||||
<EmbeddedResource Remove="SerinExpression\**" />
|
||||
<None Remove="bin\**" />
|
||||
<None Remove="SerinExpression\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="DynamicContext.cs" />
|
||||
<Compile Remove="Tool\Attribute.cs" />
|
||||
<Compile Remove="Tool\DynamicTool.cs" />
|
||||
<Compile Remove="Tool\TcsSignal.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LibraryCore\Serein.Library.Core.csproj" />
|
||||
<ProjectReference Include="..\Library.Framework\Serein.Library.Framework.csproj" />
|
||||
<ProjectReference Include="..\Serein.Library.Api\Serein.Library.Api.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -17,6 +17,19 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="DynamicContext.cs" />
|
||||
<Compile Remove="Tool\Attribute.cs" />
|
||||
<Compile Remove="Tool\DynamicTool.cs" />
|
||||
<Compile Remove="Tool\TcsSignal.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Library.Core\Serein.Library.Core.csproj" />
|
||||
<ProjectReference Include="..\Library.Framework\Serein.Library.Framework.csproj" />
|
||||
<ProjectReference Include="..\Library\Serein.Library.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.NodeFlow
|
||||
namespace Serein.NodeFlow.Tool
|
||||
{
|
||||
|
||||
public enum DynamicNodeType
|
||||
@@ -1,5 +1,6 @@
|
||||
using Serein.Library.IOC;
|
||||
using Serein.NodeFlow;
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Attributes;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Reflection;
|
||||
|
||||
@@ -27,16 +28,16 @@ public static class DelegateGenerator
|
||||
/// <param name="serviceContainer"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public static ConcurrentDictionary<string, MethodDetails> GenerateMethodDetails(IServiceContainer serviceContainer, Type type)
|
||||
public static ConcurrentDictionary<string, MethodDetails> GenerateMethodDetails(ISereinIoc serviceContainer, Type type, bool isNetFramework)
|
||||
{
|
||||
var methodDetailsDictionary = new ConcurrentDictionary<string, MethodDetails>();
|
||||
var assemblyName = type.Assembly.GetName().Name;
|
||||
var methods = GetMethodsToProcess(type);
|
||||
var methods = GetMethodsToProcess(type, isNetFramework);
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
|
||||
var methodDetails = CreateMethodDetails(serviceContainer, type, method, assemblyName);
|
||||
var methodDetails = CreateMethodDetails(serviceContainer, type, method, assemblyName, isNetFramework);
|
||||
|
||||
methodDetailsDictionary.TryAdd(methodDetails.MethodName, methodDetails);
|
||||
}
|
||||
@@ -47,48 +48,56 @@ public static class DelegateGenerator
|
||||
/// <summary>
|
||||
/// 获取处理方法
|
||||
/// </summary>
|
||||
private static IEnumerable<MethodInfo> GetMethodsToProcess(Type type)
|
||||
private static IEnumerable<MethodInfo> GetMethodsToProcess(Type type, bool isNetFramework)
|
||||
{
|
||||
return type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
|
||||
.Where(m => m.GetCustomAttribute<MethodDetailAttribute>()?.Scan == true);
|
||||
if (isNetFramework)
|
||||
{
|
||||
|
||||
return type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
|
||||
.Where(m => m.GetCustomAttribute<NodeActionAttribute>()?.Scan == true);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
return type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
|
||||
.Where(m => m.GetCustomAttribute<NodeActionAttribute>()?.Scan == true);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建方法信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static MethodDetails CreateMethodDetails(IServiceContainer serviceContainer, Type type, MethodInfo method, string assemblyName)
|
||||
private static MethodDetails CreateMethodDetails(ISereinIoc serviceContainer, Type type, MethodInfo method, string assemblyName, bool isNetFramework)
|
||||
{
|
||||
var methodName = method.Name;
|
||||
var attribute = method.GetCustomAttribute<MethodDetailAttribute>();
|
||||
|
||||
var explicitDataOfParameters = GetExplicitDataOfParameters(method.GetParameters());
|
||||
// 生成委托
|
||||
var methodDelegate = GenerateMethodDelegate(type, // 方法所在的对象类型
|
||||
method, // 方法信息
|
||||
method.GetParameters(),// 方法参数
|
||||
method.ReturnType);// 返回值
|
||||
|
||||
var methodName = method.Name;
|
||||
var attribute = method.GetCustomAttribute<NodeActionAttribute>();
|
||||
var explicitDataOfParameters = GetExplicitDataOfParameters(method.GetParameters());
|
||||
// 生成委托
|
||||
var methodDelegate = GenerateMethodDelegate(type, // 方法所在的对象类型
|
||||
method, // 方法信息
|
||||
method.GetParameters(),// 方法参数
|
||||
method.ReturnType);// 返回值
|
||||
|
||||
|
||||
var dllTypeName = $"{assemblyName}.{type.Name}";
|
||||
serviceContainer.Register(type);
|
||||
object instance = serviceContainer.GetOrCreateServiceInstance(type);
|
||||
var dllTypeMethodName = $"{assemblyName}.{type.Name}.{method.Name}";
|
||||
|
||||
|
||||
|
||||
return new MethodDetails
|
||||
{
|
||||
ActingInstanceType = type,
|
||||
ActingInstance = instance,
|
||||
MethodName = dllTypeMethodName,
|
||||
MethodDelegate = methodDelegate,
|
||||
MethodDynamicType = attribute.MethodDynamicType,
|
||||
MethodLockName = attribute.LockName,
|
||||
MethodTips = attribute.MethodTips,
|
||||
ExplicitDatas = explicitDataOfParameters,
|
||||
ReturnType = method.ReturnType,
|
||||
};
|
||||
var dllTypeName = $"{assemblyName}.{type.Name}";
|
||||
serviceContainer.Register(type);
|
||||
object instance = serviceContainer.GetOrCreateServiceInstance(type);
|
||||
var dllTypeMethodName = $"{assemblyName}.{type.Name}.{method.Name}";
|
||||
|
||||
return new MethodDetails
|
||||
{
|
||||
ActingInstanceType = type,
|
||||
ActingInstance = instance,
|
||||
MethodName = dllTypeMethodName,
|
||||
MethodDelegate = methodDelegate,
|
||||
MethodDynamicType = attribute.MethodDynamicType,
|
||||
MethodLockName = attribute.LockName,
|
||||
MethodTips = attribute.MethodTips,
|
||||
ExplicitDatas = explicitDataOfParameters,
|
||||
ReturnType = method.ReturnType,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
private static ExplicitData[] GetExplicitDataOfParameters(ParameterInfo[] parameters)
|
||||
@@ -162,7 +171,8 @@ public static class DelegateGenerator
|
||||
return ExpressionHelper.MethodCaller(type, methodInfo, parameterTypes);
|
||||
}
|
||||
}
|
||||
else if (returnType == typeof(Task<FlipflopContext>)) // 触发器
|
||||
// else if (returnType == typeof(Task<FlipflopContext)) // 触发器
|
||||
else if (FlipflopFunc.IsTaskOfFlipflop(returnType)) // 触发器
|
||||
{
|
||||
if (parameterCount == 0)
|
||||
{
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Serein.Library.Api;
|
||||
using Serein.Library.Core.NodeFlow;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Serein.NodeFlow;
|
||||
|
||||
namespace Serein.NodeFlow.Tool
|
||||
{
|
||||
@@ -325,12 +326,22 @@ namespace Serein.NodeFlow.Tool
|
||||
convertedArgs
|
||||
);
|
||||
|
||||
// 创建 lambda 表达式
|
||||
var lambda = Expression.Lambda<Func<object, object[], Task<FlipflopContext>>>(
|
||||
Expression.Convert(methodCall, typeof(Task<FlipflopContext>)),
|
||||
instanceParam,
|
||||
argsParam
|
||||
);
|
||||
// 创建 lambda 表达式
|
||||
var lambda = Expression.Lambda<Func<object, object[], Task<IFlipflopContext>>>(
|
||||
Expression.Convert(methodCall, typeof(Task<IFlipflopContext>)),
|
||||
instanceParam,
|
||||
argsParam
|
||||
);
|
||||
//获取返回类型
|
||||
//var returnType = methodInfo.ReturnType;
|
||||
//var lambda = Expression.Lambda(
|
||||
// typeof(Func<,,>).MakeGenericType(typeof(object), typeof(object[]), returnType),
|
||||
// Expression.Convert(methodCall, returnType),
|
||||
// instanceParam,
|
||||
// argsParam
|
||||
// );
|
||||
|
||||
|
||||
//var resule = task.DynamicInvoke((object)[Activator.CreateInstance(type), [new DynamicContext(null)]]);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
337
NodeFlow/Tool/SerinExpression/ConditionResolver.cs
Normal file
337
NodeFlow/Tool/SerinExpression/ConditionResolver.cs
Normal file
@@ -0,0 +1,337 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SerinExpression
|
||||
{
|
||||
/// <summary>
|
||||
/// 条件解析抽象类
|
||||
/// </summary>
|
||||
public abstract class ConditionResolver
|
||||
{
|
||||
public abstract bool Evaluate(object obj);
|
||||
}
|
||||
|
||||
public class PassConditionResolver : ConditionResolver
|
||||
{
|
||||
public Operator Op { get; set; }
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
return Op switch
|
||||
{
|
||||
Operator.Pass => true,
|
||||
Operator.NotPass => false,
|
||||
_ => throw new NotSupportedException("不支持的条件类型")
|
||||
};
|
||||
}
|
||||
|
||||
public enum Operator
|
||||
{
|
||||
Pass,
|
||||
NotPass,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public class ValueTypeConditionResolver<T> : ConditionResolver 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)
|
||||
{
|
||||
if (obj is T typedObj)
|
||||
{
|
||||
double numericValue = Convert.ToDouble(typedObj);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public class BoolConditionResolver : ConditionResolver
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
public class StringConditionResolver : ConditionResolver
|
||||
{
|
||||
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);
|
||||
}*/
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public class MemberConditionResolver<T> : ConditionResolver 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 override bool Evaluate(object? obj)
|
||||
{
|
||||
//object? memberValue = GetMemberValue(obj, MemberPath);
|
||||
if (TargetObj is T typedObj)
|
||||
{
|
||||
return new ValueTypeConditionResolver<T>
|
||||
{
|
||||
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;
|
||||
//}
|
||||
}
|
||||
|
||||
public class MemberStringConditionResolver : ConditionResolver
|
||||
{
|
||||
|
||||
public string MemberPath { get; set; }
|
||||
|
||||
public StringConditionResolver.Operator Op { get; set; }
|
||||
|
||||
public string Value { get; set; }
|
||||
|
||||
|
||||
public override bool Evaluate(object obj)
|
||||
{
|
||||
object memberValue = GetMemberValue(obj, MemberPath);
|
||||
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('.');
|
||||
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;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
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;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
341
NodeFlow/Tool/SerinExpression/SerinConditionParser.cs
Normal file
341
NodeFlow/Tool/SerinExpression/SerinConditionParser.cs
Normal file
@@ -0,0 +1,341 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SerinExpression
|
||||
{
|
||||
|
||||
public class SerinConditionParser
|
||||
{
|
||||
public static bool To<T>(T data, string expression)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
return ConditionParse(data, expression).Evaluate(data);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static ConditionResolver 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('.');
|
||||
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;
|
||||
}
|
||||
/// <summary>
|
||||
/// 解析对象表达式
|
||||
/// </summary>
|
||||
private static ConditionResolver ParseObjectExpression(object data, string expression)
|
||||
{
|
||||
var parts = expression.Split(' ');
|
||||
string operatorStr = parts[0];
|
||||
string valueStr = string.Join(' ', parts, 1, parts.Length - 1);
|
||||
|
||||
int typeStartIndex = expression.IndexOf('<');
|
||||
int typeEndIndex = expression.IndexOf('>');
|
||||
|
||||
string memberPath;
|
||||
Type type;
|
||||
object? targetObj;
|
||||
if (typeStartIndex + typeStartIndex == -2)
|
||||
{
|
||||
memberPath = operatorStr;
|
||||
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));
|
||||
}
|
||||
targetObj = GetMemberValue(data, memberPath);
|
||||
|
||||
Type? tempType = typeStr switch
|
||||
{
|
||||
"int" => typeof(int),
|
||||
"double" => typeof(double),
|
||||
"bool" => typeof(bool),
|
||||
"string" => typeof(string),
|
||||
_ => Type.GetType(typeStr)
|
||||
};
|
||||
type = tempType ?? throw new ArgumentException("对象表达式无效的类型声明");
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (type == typeof(int))
|
||||
{
|
||||
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])
|
||||
};
|
||||
}
|
||||
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])
|
||||
};
|
||||
|
||||
}
|
||||
else if (type == typeof(bool))
|
||||
{
|
||||
return new MemberConditionResolver<bool>
|
||||
{
|
||||
//MemberPath = memberPath,
|
||||
TargetObj = targetObj,
|
||||
Op = (ValueTypeConditionResolver<bool>.Operator)ParseBoolOperator(operatorStr)
|
||||
};
|
||||
}
|
||||
else if (type == typeof(string))
|
||||
{
|
||||
return new MemberStringConditionResolver
|
||||
{
|
||||
MemberPath = memberPath,
|
||||
Op = ParseStringOperator(operatorStr),
|
||||
Value = valueStr
|
||||
};
|
||||
}
|
||||
|
||||
throw new NotSupportedException($"Type {type} is not supported.");
|
||||
}
|
||||
|
||||
private static ConditionResolver 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 typeStr = parts[0];
|
||||
string operatorStr = parts[0];
|
||||
string valueStr = string.Join(' ', parts, 1, parts.Length - 1);
|
||||
|
||||
Type type = data.GetType();//Type.GetType(typeStr);
|
||||
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 ValueTypeConditionResolver<int>
|
||||
{
|
||||
Op = op,
|
||||
RangeStart = rangeStart,
|
||||
RangeEnd = rangeEnd,
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0]),
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
int value = int.Parse(valueStr, CultureInfo.InvariantCulture);
|
||||
return new ValueTypeConditionResolver<int>
|
||||
{
|
||||
Op = op,
|
||||
Value = value,
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0])
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
else if (type == typeof(double))
|
||||
{
|
||||
double value = double.Parse(valueStr, CultureInfo.InvariantCulture);
|
||||
return new ValueTypeConditionResolver<double>
|
||||
{
|
||||
Op = ParseValueTypeOperator<double>(operatorStr),
|
||||
Value = value,
|
||||
ArithmeticExpression = GetArithmeticExpression(parts[0])
|
||||
};
|
||||
}
|
||||
else if (type == typeof(bool))
|
||||
{
|
||||
bool value = bool.Parse(valueStr);
|
||||
return new BoolConditionResolver
|
||||
{
|
||||
Op = ParseBoolOperator(operatorStr),
|
||||
Value = value,
|
||||
};
|
||||
}
|
||||
else if (type == typeof(string))
|
||||
{
|
||||
return new StringConditionResolver
|
||||
{
|
||||
Op = ParseStringOperator(operatorStr),
|
||||
Value = valueStr
|
||||
};
|
||||
}
|
||||
|
||||
throw new NotSupportedException($"Type {type} is not supported.");
|
||||
}
|
||||
|
||||
|
||||
private static ValueTypeConditionResolver<T>.Operator ParseValueTypeOperator<T>(string operatorStr) where T : struct, IComparable<T>
|
||||
{
|
||||
return operatorStr switch
|
||||
{
|
||||
">" => ValueTypeConditionResolver<T>.Operator.GreaterThan,
|
||||
"<" => ValueTypeConditionResolver<T>.Operator.LessThan,
|
||||
"=" => ValueTypeConditionResolver<T>.Operator.Equal,
|
||||
"==" => ValueTypeConditionResolver<T>.Operator.Equal,
|
||||
">=" => ValueTypeConditionResolver<T>.Operator.GreaterThanOrEqual,
|
||||
"≥" => ValueTypeConditionResolver<T>.Operator.GreaterThanOrEqual,
|
||||
"<=" => ValueTypeConditionResolver<T>.Operator.LessThanOrEqual,
|
||||
"≤" => ValueTypeConditionResolver<T>.Operator.LessThanOrEqual,
|
||||
"equals" => ValueTypeConditionResolver<T>.Operator.Equal,
|
||||
"in" => ValueTypeConditionResolver<T>.Operator.InRange,
|
||||
"!in" => ValueTypeConditionResolver<T>.Operator.OutOfRange,
|
||||
_ => throw new ArgumentException($"Invalid operator {operatorStr} for value type.")
|
||||
};
|
||||
}
|
||||
|
||||
private static BoolConditionResolver.Operator ParseBoolOperator(string operatorStr)
|
||||
{
|
||||
return operatorStr switch
|
||||
{
|
||||
"is" => BoolConditionResolver.Operator.Is,
|
||||
"==" => BoolConditionResolver.Operator.Is,
|
||||
"equals" => BoolConditionResolver.Operator.Is,
|
||||
//"isFalse" => BoolConditionNode.Operator.IsFalse,
|
||||
_ => throw new ArgumentException($"Invalid operator {operatorStr} for bool type.")
|
||||
};
|
||||
}
|
||||
|
||||
private static StringConditionResolver.Operator ParseStringOperator(string operatorStr)
|
||||
{
|
||||
return operatorStr switch
|
||||
{
|
||||
"c" => StringConditionResolver.Operator.Contains,
|
||||
"nc" => StringConditionResolver.Operator.DoesNotContain,
|
||||
"sw" => StringConditionResolver.Operator.StartsWith,
|
||||
"ew" => StringConditionResolver.Operator.EndsWith,
|
||||
|
||||
"contains" => StringConditionResolver.Operator.Contains,
|
||||
"doesNotContain" => StringConditionResolver.Operator.DoesNotContain,
|
||||
"equals" => StringConditionResolver.Operator.Equal,
|
||||
"==" => StringConditionResolver.Operator.Equal,
|
||||
"notEquals" => StringConditionResolver.Operator.NotEqual,
|
||||
"!=" => StringConditionResolver.Operator.NotEqual,
|
||||
"startsWith" => StringConditionResolver.Operator.StartsWith,
|
||||
"endsWith" => StringConditionResolver.Operator.EndsWith,
|
||||
_ => throw new ArgumentException($"Invalid operator {operatorStr} for string type.")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
216
NodeFlow/Tool/SerinExpression/SerinExpressionEvaluator.cs
Normal file
216
NodeFlow/Tool/SerinExpression/SerinExpressionEvaluator.cs
Normal file
@@ -0,0 +1,216 @@
|
||||
using System.Data;
|
||||
|
||||
namespace Serein.NodeFlow.Tool.SerinExpression
|
||||
{
|
||||
public class SerinArithmeticExpressionEvaluator
|
||||
{
|
||||
private static readonly DataTable table = new DataTable();
|
||||
|
||||
public static double Evaluate(string expression, double inputValue)
|
||||
{
|
||||
// 替换占位符@为输入值
|
||||
expression = expression.Replace("@", inputValue.ToString());
|
||||
try
|
||||
{
|
||||
// 使用 DataTable.Compute 方法计算表达式
|
||||
var result = table.Compute(expression, string.Empty);
|
||||
return Convert.ToDouble(result);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new ArgumentException("Invalid arithmetic expression.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SerinExpressionEvaluator
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="expression">表达式</param>
|
||||
/// <param name="targetObJ">操作对象</param>
|
||||
/// <param name="isChange">是否改变了对象(get语法)</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);
|
||||
if (parts.Length != 2)
|
||||
{
|
||||
throw new ArgumentException("Invalid expression format.");
|
||||
}
|
||||
|
||||
var operation = parts[0].ToLower();
|
||||
var operand = parts[1][0] == '.' ? parts[1][1..] : parts[1];
|
||||
|
||||
var result = operation switch
|
||||
{
|
||||
"@num" => ComputedNumber(targetObJ, operand),
|
||||
"@call" => InvokeMethod(targetObJ, operand),
|
||||
"@get" => GetMember(targetObJ, operand),
|
||||
"@set" => SetMember(targetObJ, operand),
|
||||
_ => throw new NotSupportedException($"Operation {operation} is not supported.")
|
||||
};
|
||||
|
||||
isChange = operation switch
|
||||
{
|
||||
"@num" => true,
|
||||
"@call" => true,
|
||||
"@get" => true,
|
||||
"@set" => false,
|
||||
_ => throw new NotSupportedException($"Operation {operation} is not supported.")
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
private static readonly char[] separator = ['(', ')'];
|
||||
private static readonly char[] separatorArray = [','];
|
||||
|
||||
private static object InvokeMethod(object target, string methodCall)
|
||||
{
|
||||
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);
|
||||
if (method == null)
|
||||
{
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
private static object GetMember(object target, string memberPath)
|
||||
{
|
||||
var members = memberPath.Split('.');
|
||||
foreach (var member in members)
|
||||
{
|
||||
|
||||
if (target == null) return null;
|
||||
|
||||
|
||||
var property = target.GetType().GetProperty(member);
|
||||
if (property != null)
|
||||
{
|
||||
|
||||
target = property.GetValue(target);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
var field = target.GetType().GetField(member);
|
||||
if (field != null)
|
||||
{
|
||||
|
||||
target = field.GetValue(target);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Member {member} not found on target.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return target;
|
||||
|
||||
}
|
||||
|
||||
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 property = target.GetType().GetProperty(member);
|
||||
|
||||
if (property != null)
|
||||
{
|
||||
|
||||
target = property.GetValue(target);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
var field = target.GetType().GetField(member);
|
||||
if (field != null)
|
||||
{
|
||||
|
||||
target = field.GetValue(target);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Member {member} not found on target.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var lastMember = members.Last();
|
||||
|
||||
var lastProperty = target.GetType().GetProperty(lastMember);
|
||||
|
||||
if (lastProperty != null)
|
||||
{
|
||||
var convertedValue = Convert.ChangeType(value, lastProperty.PropertyType);
|
||||
lastProperty.SetValue(target, convertedValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
var lastField = target.GetType().GetField(lastMember);
|
||||
if (lastField != null)
|
||||
{
|
||||
var convertedValue = Convert.ChangeType(value, lastField.FieldType);
|
||||
lastField.SetValue(target, convertedValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException($"Member {lastMember} not found on target.");
|
||||
}
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
private static double ComputedNumber(object value, string expression)
|
||||
{
|
||||
double numericValue = Convert.ToDouble(value);
|
||||
if (!string.IsNullOrEmpty(expression))
|
||||
{
|
||||
numericValue = SerinArithmeticExpressionEvaluator.Evaluate(expression, numericValue);
|
||||
}
|
||||
|
||||
return numericValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ namespace Serein.NodeFlow.Tool
|
||||
{
|
||||
//public ConcurrentDictionary<TSignal, Queue<TaskCompletionSource<object>>> TcsEvent { get; } = new();
|
||||
public ConcurrentDictionary<TSignal, TaskCompletionSource<object>> TcsEvent { get; } = new();
|
||||
public ConcurrentDictionary<TSignal, object> TcsValue { get; } = new();
|
||||
|
||||
public ConcurrentDictionary<TSignal, object> TcsLock { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 触发信号
|
||||
@@ -28,30 +29,36 @@ namespace Serein.NodeFlow.Tool
|
||||
/// <returns>是否成功触发</returns>
|
||||
public bool TriggerSignal<T>(TSignal signal, T value)
|
||||
{
|
||||
if (TcsEvent.TryRemove(signal, out var waitTcs))
|
||||
var tcsLock = TcsLock.GetOrAdd(signal, new object());
|
||||
lock (tcsLock)
|
||||
{
|
||||
waitTcs.SetResult(value);
|
||||
return true;
|
||||
if (TcsEvent.TryRemove(signal, out var waitTcs))
|
||||
{
|
||||
waitTcs.SetResult(value);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public TaskCompletionSource<object> CreateTcs(TSignal signal)
|
||||
{
|
||||
var tcs = TcsEvent.GetOrAdd(signal,_ = new TaskCompletionSource<object>());
|
||||
return tcs;
|
||||
var tcsLock = TcsLock.GetOrAdd(signal, new object());
|
||||
lock (tcsLock)
|
||||
{
|
||||
var tcs = TcsEvent.GetOrAdd(signal, new TaskCompletionSource<object>());
|
||||
return tcs;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void CancelTask()
|
||||
{
|
||||
lock (TcsEvent)
|
||||
foreach (var tcs in TcsEvent.Values)
|
||||
{
|
||||
foreach (var tcs in TcsEvent.Values)
|
||||
{
|
||||
tcs.SetException(new TcsSignalException("任务取消"));
|
||||
}
|
||||
TcsEvent.Clear();
|
||||
tcs.SetException(new TcsSignalException("任务取消"));
|
||||
}
|
||||
TcsEvent.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user