mirror of
https://gitee.com/langsisi_admin/serein-flow
synced 2026-03-19 16:06:33 +08:00
GIT练习
This commit is contained in:
13
Library/DynamicFlow/Api.cs
Normal file
13
Library/DynamicFlow/Api.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.DynamicFlow
|
||||
{
|
||||
public interface IDynamicFlowNode
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
73
Library/DynamicFlow/Attribute.cs
Normal file
73
Library/DynamicFlow/Attribute.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.DynamicFlow
|
||||
{
|
||||
|
||||
public enum DynamicNodeType
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化
|
||||
/// </summary>
|
||||
Init,
|
||||
/// <summary>
|
||||
/// 开始载入
|
||||
/// </summary>
|
||||
Loading,
|
||||
/// <summary>
|
||||
/// 结束
|
||||
/// </summary>
|
||||
Exit,
|
||||
|
||||
/// <summary>
|
||||
/// 触发器
|
||||
/// </summary>
|
||||
Flipflop,
|
||||
/// <summary>
|
||||
/// 条件节点
|
||||
/// </summary>
|
||||
Condition,
|
||||
/// <summary>
|
||||
/// 动作节点
|
||||
/// </summary>
|
||||
Action,
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 用来判断一个类是否需要注册并构建实例(单例模式场景使用)
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class)]
|
||||
public class DynamicFlowAttribute(bool scan = true) : Attribute
|
||||
{
|
||||
public bool Scan { get; set; } = scan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标记一个方法是什么类型,加载dll后用来拖拽到画布中
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public class MethodDetailAttribute(DynamicNodeType methodDynamicType,
|
||||
string methodTips = "",
|
||||
bool scan = true,
|
||||
string lockName = "") : Attribute
|
||||
{
|
||||
public bool Scan { get; set; } = scan;
|
||||
public string MethodTips { get; } = methodTips;
|
||||
public DynamicNodeType MethodDynamicType { get; } = methodDynamicType;
|
||||
public string LockName { get; } = lockName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否为显式参数
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Parameter)]
|
||||
public class ExplicitAttribute : Attribute // where TEnum : Enum
|
||||
{
|
||||
}
|
||||
|
||||
}
|
||||
165
Library/DynamicFlow/DynamicContext.cs
Normal file
165
Library/DynamicFlow/DynamicContext.cs
Normal file
@@ -0,0 +1,165 @@
|
||||
using DynamicDemo.Node;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static System.Collections.Specialized.BitVector32;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
|
||||
namespace Serein.DynamicFlow
|
||||
{
|
||||
|
||||
public enum FfState
|
||||
{
|
||||
Succeed,
|
||||
Cancel,
|
||||
}
|
||||
/// <summary>
|
||||
/// 触发器上下文
|
||||
/// </summary>
|
||||
public class FlipflopContext
|
||||
{
|
||||
public FfState State { get; set; }
|
||||
public object? Data { get; set; }
|
||||
/*public FlipflopContext()
|
||||
{
|
||||
State = FfState.Cancel;
|
||||
}*/
|
||||
public FlipflopContext(FfState ffState,object? data = null)
|
||||
{
|
||||
State = ffState;
|
||||
Data = data;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 动态流程上下文
|
||||
/// </summary>
|
||||
public class DynamicContext(IServiceContainer serviceContainer)
|
||||
{
|
||||
|
||||
private readonly string contextGuid = "";//System.Guid.NewGuid().ToString();
|
||||
|
||||
public IServiceContainer ServiceContainer { get; } = serviceContainer;
|
||||
private List<Type> InitServices { get; set; } = [];
|
||||
|
||||
// private ConcurrentDictionary<string, object?> ContextData { get; set; } = [];
|
||||
|
||||
//public void SetFlowData(object data)
|
||||
//{
|
||||
// var threadId = Thread.CurrentThread.ManagedThreadId.ToString();
|
||||
// var name = $"{threadId}.{contextGuid}FlowData";
|
||||
// SetData(name,data);
|
||||
//}
|
||||
//public object GetFlowData(bool IsRetain = false)
|
||||
//{
|
||||
// var threadId = Thread.CurrentThread.ManagedThreadId.ToString();
|
||||
// var name = $"{threadId}.{contextGuid}FlowData";
|
||||
// if (IsRetain)
|
||||
// {
|
||||
// return GetData(name);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// return GetAndRemoteData(name);
|
||||
|
||||
// }
|
||||
//}
|
||||
|
||||
|
||||
public void InitService<T>()
|
||||
{
|
||||
InitService(typeof(T));
|
||||
}
|
||||
public void InitService(Type type)
|
||||
{
|
||||
if (!InitServices.Contains(type))
|
||||
{
|
||||
InitServices.Add(type);
|
||||
}
|
||||
else
|
||||
{
|
||||
//throw new Exception("初始化时试图添加已存在的类型:"+type.Name);
|
||||
Console.WriteLine("初始化时试图添加已存在的类型:" + type.Name);
|
||||
}
|
||||
}
|
||||
public void Biuld()
|
||||
{
|
||||
foreach (var item in InitServices)
|
||||
{
|
||||
ServiceContainer.Register(item);
|
||||
}
|
||||
ServiceContainer.Build();
|
||||
}
|
||||
|
||||
//public object? RemoveData(string key)
|
||||
//{
|
||||
// if (ContextData.Remove(key, out var data))
|
||||
// {
|
||||
// return data;
|
||||
// }
|
||||
// return null;
|
||||
//}
|
||||
|
||||
//public void SetData<T>(string key, T value)
|
||||
//{
|
||||
// ContextData[key] = value;
|
||||
//}
|
||||
|
||||
//public T? GetData<T>(string key)
|
||||
//{
|
||||
// if (ContextData.TryGetValue(key, out object? value))
|
||||
// {
|
||||
// if(value == null)
|
||||
// {
|
||||
// return default;
|
||||
// }
|
||||
// if (value.GetType() == typeof(T))
|
||||
// {
|
||||
// return (T)value;
|
||||
// }
|
||||
|
||||
// }
|
||||
// return default;
|
||||
//}
|
||||
|
||||
//public object? GetData(string key)
|
||||
//{
|
||||
// if (ContextData.TryGetValue(key, out object? value))
|
||||
// {
|
||||
// return value;
|
||||
// }
|
||||
// return null;
|
||||
//}
|
||||
|
||||
|
||||
//public ConcurrentDictionary<string,Task> FlipFlopTasks { get; set; } = [];
|
||||
|
||||
public NodeRunTcs NodeRunCts { get; set; }
|
||||
public Task CreateTimingTask(Action action, int time = 100, int count = -1)
|
||||
{
|
||||
NodeRunCts ??= ServiceContainer.Get<NodeRunTcs>();
|
||||
return Task.Factory.StartNew(async () =>
|
||||
{
|
||||
for(int i = 0; i < count; i++)
|
||||
{
|
||||
NodeRunCts.Token.ThrowIfCancellationRequested();
|
||||
await time;
|
||||
action.Invoke();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public static class MyExtensions
|
||||
{
|
||||
public static TaskAwaiter GetAwaiter(this int i) => Task.Delay(i).GetAwaiter();
|
||||
}
|
||||
|
||||
|
||||
// if (time <= 0) throw new ArgumentException("时间不能≤0");
|
||||
}
|
||||
218
Library/DynamicFlow/MethodDetails.cs
Normal file
218
Library/DynamicFlow/MethodDetails.cs
Normal file
@@ -0,0 +1,218 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static Dm.net.buffer.ByteArrayBuffer;
|
||||
|
||||
namespace Serein.DynamicFlow
|
||||
{
|
||||
/// <summary>
|
||||
/// 显式参数
|
||||
/// </summary>
|
||||
public class ExplicitData
|
||||
{
|
||||
/// <summary>
|
||||
/// 索引
|
||||
/// </summary>
|
||||
public int Index { get; set; }
|
||||
/// <summary>
|
||||
/// 是否为显式参数
|
||||
/// </summary>
|
||||
public bool IsExplicitData { get; set; }
|
||||
/// <summary>
|
||||
/// 显式类型
|
||||
/// </summary>
|
||||
public Type? ExplicitType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 显示类型编号>
|
||||
/// </summary>
|
||||
public string ExplicitTypeName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 方法需要的类型
|
||||
/// </summary>
|
||||
public Type DataType { get; set; }
|
||||
/// <summary>
|
||||
/// 方法入参参数名称
|
||||
/// </summary>
|
||||
public string ParameterName { get; set; }
|
||||
/// <summary>
|
||||
/// 入参值
|
||||
/// </summary>
|
||||
public string DataValue { get; set; }
|
||||
|
||||
public string[] Items { get; set; }
|
||||
|
||||
|
||||
|
||||
public ExplicitData Clone() => new()
|
||||
{
|
||||
Index = Index,
|
||||
IsExplicitData = IsExplicitData,
|
||||
ExplicitType = ExplicitType,
|
||||
DataType = DataType,
|
||||
ParameterName = ParameterName,
|
||||
ExplicitTypeName = ExplicitTypeName,
|
||||
DataValue = string.IsNullOrEmpty(DataValue) ? string.Empty : DataValue,
|
||||
Items = [.. Items],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class MethodDetails
|
||||
{
|
||||
public MethodDetails CpoyNew()
|
||||
{
|
||||
return new MethodDetails
|
||||
{
|
||||
ActingInstance = ActingInstance,
|
||||
ActingInstanceType = ActingInstanceType,
|
||||
MethodDelegate = MethodDelegate,
|
||||
MethodDynamicType = MethodDynamicType,
|
||||
MethodGuid = Guid.NewGuid().ToString(),
|
||||
MethodTips = MethodTips + " Cpoy",
|
||||
//ParameterTypes = ParameterTypes,
|
||||
ReturnType = ReturnType,
|
||||
MethodName = MethodName,
|
||||
MethodLockName = MethodLockName,
|
||||
//ExplicitDataValues = ExplicitDataValues.Select(it => "").ToArray(),
|
||||
ExplicitDatas = ExplicitDatas.Select(it => it.Clone()).ToArray(),
|
||||
//IsExplicits = IsExplicits,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 作用实例
|
||||
/// </summary>
|
||||
public Type ActingInstanceType { get; set; }
|
||||
/// <summary>
|
||||
/// 作用实例
|
||||
/// </summary>
|
||||
public object ActingInstance { get; set; }
|
||||
/// <summary>
|
||||
/// 方法GUID
|
||||
/// </summary>
|
||||
public string MethodGuid { get; set; }
|
||||
/// <summary>
|
||||
/// 方法名称
|
||||
/// </summary>
|
||||
public string MethodName { get; set; }
|
||||
/// <summary>
|
||||
/// 方法委托
|
||||
/// </summary>
|
||||
public Delegate MethodDelegate { get; set; }
|
||||
/// <summary>
|
||||
/// 节点类型
|
||||
/// </summary>
|
||||
public DynamicNodeType MethodDynamicType { get; set; }
|
||||
/// <summary>
|
||||
/// 锁名称
|
||||
/// </summary>
|
||||
public string MethodLockName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 方法说明
|
||||
/// </summary>
|
||||
public string MethodTips { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 参数内容
|
||||
/// </summary>
|
||||
public ExplicitData[] ExplicitDatas { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 出参类型
|
||||
/// </summary>
|
||||
public Type ReturnType { 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))
|
||||
{
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
158
Library/DynamicFlow/NodeFlowStarter.cs
Normal file
158
Library/DynamicFlow/NodeFlowStarter.cs
Normal file
@@ -0,0 +1,158 @@
|
||||
using Serein;
|
||||
using Serein.DynamicFlow;
|
||||
using Serein.DynamicFlow.NodeModel;
|
||||
using Serein.DynamicFlow.Tool;
|
||||
using Serein.Web;
|
||||
using SqlSugar;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace DynamicDemo.Node
|
||||
{
|
||||
|
||||
public class NodeRunTcs: CancellationTokenSource
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public class NodeFlowStarter(IServiceContainer serviceContainer,List<MethodDetails> methodDetails)
|
||||
{
|
||||
private readonly IServiceContainer ServiceContainer = serviceContainer;
|
||||
private readonly List<MethodDetails> methodDetails = methodDetails;
|
||||
private Action ExitAction = null;
|
||||
private DynamicContext context = null;
|
||||
|
||||
public NodeRunTcs MainCts;
|
||||
|
||||
/// <summary>
|
||||
/// 运行测试
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
public async Task RunAsync(List<NodeBase> nodes)
|
||||
{
|
||||
var startNode = nodes.FirstOrDefault(p => p.IsStart);
|
||||
if (startNode == null) { return; }
|
||||
context = new(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();
|
||||
ExitAction = () =>
|
||||
{
|
||||
ServiceContainer.Run<WebServer>((web) =>
|
||||
{
|
||||
web?.Stop();
|
||||
});
|
||||
foreach (MethodDetails? md in exitMethods)
|
||||
{
|
||||
object?[]? args = [context];
|
||||
object?[]? data = [md.ActingInstance, args];
|
||||
md.MethodDelegate.DynamicInvoke(data);
|
||||
}
|
||||
if(context != null && context.NodeRunCts != null && !context.NodeRunCts.IsCancellationRequested)
|
||||
{
|
||||
context.NodeRunCts.Cancel();
|
||||
}
|
||||
if (MainCts!=null && !MainCts.IsCancellationRequested) MainCts.Cancel();
|
||||
ServiceContainer.Reset();
|
||||
};
|
||||
|
||||
|
||||
foreach (var md in initMethods) // 初始化 - 调用方法
|
||||
{
|
||||
//md.ActingInstance = context.ServiceContainer.Get(md.ActingInstanceType);
|
||||
object?[]? args = [context];
|
||||
object?[]? data = [md.ActingInstance, args];
|
||||
md.MethodDelegate.DynamicInvoke(data);
|
||||
}
|
||||
context.Biuld();
|
||||
|
||||
foreach (var md in loadingMethods) // 加载
|
||||
{
|
||||
//md.ActingInstance = context.ServiceContainer.Get(md.ActingInstanceType);
|
||||
object?[]? args = [context];
|
||||
object?[]? data = [md.ActingInstance, args];
|
||||
md.MethodDelegate.DynamicInvoke(data);
|
||||
}
|
||||
|
||||
var flipflopNodes = nodes.Where(it => it.MethodDetails?.MethodDynamicType == DynamicNodeType.Flipflop
|
||||
&& it.PreviousNodes.Count == 0
|
||||
&& it.IsStart != true).ToArray();
|
||||
|
||||
var singleFlipflopNodes = flipflopNodes.Select(it => (SingleFlipflopNode)it).ToArray();
|
||||
|
||||
// 使用 TaskCompletionSource 创建未启动的任务
|
||||
var tasks = singleFlipflopNodes.Select(async node =>
|
||||
{
|
||||
await FlipflopExecute(node);
|
||||
}).ToArray();
|
||||
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
await Task.WhenAll([startNode.ExecuteStack(context),.. tasks]);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await Console.Out.WriteLineAsync(ex.ToString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private async Task FlipflopExecute(SingleFlipflopNode singleFlipFlopNode)
|
||||
{
|
||||
DynamicContext context = new DynamicContext(ServiceContainer);
|
||||
MethodDetails md = singleFlipFlopNode.MethodDetails;
|
||||
|
||||
try
|
||||
{
|
||||
if (!DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var func = md.ExplicitDatas.Length == 0 ? ((Func<object, object, Task<FlipflopContext>>)del) : ((Func<object, object[], Task<FlipflopContext>>)del);
|
||||
|
||||
while (!MainCts.IsCancellationRequested) // 循环中直到栈为空才会退出
|
||||
{
|
||||
object?[]? parameters = singleFlipFlopNode.GetParameters(context, md);
|
||||
// 调用委托并获取结果
|
||||
FlipflopContext flipflopContext = await func.Invoke(md.ActingInstance, parameters);
|
||||
|
||||
if (flipflopContext == null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else if (flipflopContext.State == FfState.Cancel)
|
||||
{
|
||||
break;
|
||||
}
|
||||
else if (flipflopContext.State == FfState.Succeed)
|
||||
{
|
||||
singleFlipFlopNode.FlowState = true;
|
||||
singleFlipFlopNode.FlowData = flipflopContext.Data;
|
||||
var tasks = singleFlipFlopNode.TrueBranch.Select(nextNode =>
|
||||
{
|
||||
var context = new DynamicContext(ServiceContainer);
|
||||
nextNode.PreviousNode = singleFlipFlopNode;
|
||||
return nextNode.ExecuteStack(context);
|
||||
}).ToArray();
|
||||
Task.WaitAll(tasks);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await Console.Out.WriteLineAsync(ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void Exit()
|
||||
{
|
||||
ExitAction?.Invoke();
|
||||
}
|
||||
}
|
||||
}
|
||||
54
Library/DynamicFlow/NodeModel/CompositeActionNode.cs
Normal file
54
Library/DynamicFlow/NodeModel/CompositeActionNode.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using Serein.DynamicFlow;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 组合动作节点(用于动作区域)
|
||||
/// </summary>
|
||||
public class CompositeActionNode : NodeBase
|
||||
{
|
||||
public List<SingleActionNode> ActionNodes;
|
||||
/// <summary>
|
||||
/// 组合动作节点(用于动作区域)
|
||||
/// </summary>
|
||||
public CompositeActionNode(List<SingleActionNode> actionNodes)
|
||||
{
|
||||
ActionNodes = actionNodes;
|
||||
}
|
||||
public void AddNode(SingleActionNode node)
|
||||
{
|
||||
ActionNodes.Add(node);
|
||||
MethodDetails ??= node.MethodDetails;
|
||||
}
|
||||
|
||||
//public override void Execute(DynamicContext context)
|
||||
//{
|
||||
// //Dictionary<int,object> dict = new Dictionary<int,object>();
|
||||
// for (int i = 0; i < ActionNodes.Count; i++)
|
||||
// {
|
||||
// SingleActionNode? action = ActionNodes[i];
|
||||
// try
|
||||
// {
|
||||
// action.Execute(context);
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// Debug.Write(ex.Message);
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
|
||||
// CurrentState = true;
|
||||
// return;
|
||||
|
||||
|
||||
// /*foreach (var nextNode in TrueBranchNextNodes)
|
||||
// {
|
||||
// nextNode.ExecuteStack(context);
|
||||
// }*/
|
||||
//}
|
||||
}
|
||||
|
||||
}
|
||||
69
Library/DynamicFlow/NodeModel/CompositeConditionNode.cs
Normal file
69
Library/DynamicFlow/NodeModel/CompositeConditionNode.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using Serein.DynamicFlow.Tool;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 组合条件节点(用于条件区域)
|
||||
/// </summary>
|
||||
public class CompositeConditionNode : NodeBase
|
||||
{
|
||||
public List<SingleConditionNode> ConditionNodes { get; } =[];
|
||||
|
||||
|
||||
public void AddNode(SingleConditionNode node)
|
||||
{
|
||||
ConditionNodes.Add(node);
|
||||
MethodDetails ??= node.MethodDetails;
|
||||
}
|
||||
|
||||
public override object? Execute(DynamicContext context)
|
||||
{
|
||||
// bool allTrue = ConditionNodes.All(condition => Judge(context,condition.MethodDetails));
|
||||
// bool IsAllTrue = true; // 初始化为 true
|
||||
FlowState = true;
|
||||
foreach (SingleConditionNode? node in ConditionNodes)
|
||||
{
|
||||
if (!Judge(context, node))
|
||||
{
|
||||
FlowState = false;
|
||||
break;// 一旦发现条件为假,立即退出循环
|
||||
}
|
||||
}
|
||||
|
||||
return PreviousNode?.FlowData;
|
||||
//if (IsAllTrue)
|
||||
//{
|
||||
// foreach (var nextNode in TrueBranchNextNodes)
|
||||
// {
|
||||
// nextNode.ExecuteStack(context);
|
||||
// }
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// foreach (var nextNode in FalseBranchNextNodes)
|
||||
// {
|
||||
// nextNode.ExecuteStack(context);
|
||||
// }
|
||||
//}
|
||||
}
|
||||
private bool Judge(DynamicContext context, SingleConditionNode node)
|
||||
{
|
||||
try
|
||||
{
|
||||
node.Execute(context);
|
||||
return node.FlowState;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Write(ex.Message);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
12
Library/DynamicFlow/NodeModel/CompositeLoopNode.cs
Normal file
12
Library/DynamicFlow/NodeModel/CompositeLoopNode.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
public class CompositeLoopNode : NodeBase
|
||||
{
|
||||
}
|
||||
}
|
||||
449
Library/DynamicFlow/NodeModel/NodeBase.cs
Normal file
449
Library/DynamicFlow/NodeModel/NodeBase.cs
Normal file
@@ -0,0 +1,449 @@
|
||||
using Serein.DynamicFlow;
|
||||
using Serein.DynamicFlow.Tool;
|
||||
using Newtonsoft.Json;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
|
||||
public enum ConnectionType
|
||||
{
|
||||
IsTrue,
|
||||
IsFalse,
|
||||
IsEx,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 节点基类(数据):条件控件,动作控件,条件区域,动作区域
|
||||
/// </summary>
|
||||
public abstract class NodeBase : IDynamicFlowNode
|
||||
{
|
||||
public MethodDetails MethodDetails { get; set; }
|
||||
public string Guid { get; set; }
|
||||
public string DisplayName { get; set; }
|
||||
public bool IsStart { get; set; }
|
||||
public string DelegateName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 运行时的上一节点
|
||||
/// </summary>
|
||||
public NodeBase? PreviousNode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 上一节点集合
|
||||
/// </summary>
|
||||
public List<NodeBase> PreviousNodes { get; set; } = [];
|
||||
/// <summary>
|
||||
/// 下一节点集合(真分支)
|
||||
/// </summary>
|
||||
public List<NodeBase> TrueBranch { get; set; } = [];
|
||||
/// <summary>
|
||||
/// 下一节点集合(假分支)
|
||||
/// </summary>
|
||||
public List<NodeBase> FalseBranch { get; set; } = [];
|
||||
/// <summary>
|
||||
/// 异常分支
|
||||
/// </summary>
|
||||
public List<NodeBase> ExBranch { get; set; } = [];
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 当前状态(进入真分支还是假分支,异常分支在异常中确定)
|
||||
/// </summary>
|
||||
public bool FlowState { get; set; } = true;
|
||||
//public ConnectionType NextType { get; set; } = ConnectionType.IsTrue;
|
||||
/// <summary>
|
||||
/// 当前传递数据
|
||||
/// </summary>
|
||||
public object? FlowData { get; set; } = null;
|
||||
|
||||
|
||||
// 正常流程节点调用
|
||||
public virtual object? Execute(DynamicContext context)
|
||||
{
|
||||
MethodDetails md = MethodDetails;
|
||||
object? result = null;
|
||||
if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
|
||||
{
|
||||
if (md.ExplicitDatas.Length == 0)
|
||||
{
|
||||
if (md.ReturnType == typeof(void))
|
||||
{
|
||||
((Action<object>)del).Invoke(md.ActingInstance);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = ((Func<object, object>)del).Invoke(md.ActingInstance);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
object?[]? parameters = GetParameters(context, MethodDetails);
|
||||
if (md.ReturnType == typeof(void))
|
||||
{
|
||||
((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
|
||||
}
|
||||
}
|
||||
// context.SetFlowData(result);
|
||||
// CurrentData = result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// 触发器调用
|
||||
public virtual async Task<object?> ExecuteAsync(DynamicContext context)
|
||||
{
|
||||
MethodDetails md = MethodDetails;
|
||||
object? result = null;
|
||||
if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
|
||||
{
|
||||
if (md.ExplicitDatas.Length == 0)
|
||||
{
|
||||
// 调用委托并获取结果
|
||||
FlipflopContext flipflopContext = await ((Func<object, Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
|
||||
|
||||
if (flipflopContext != null)
|
||||
{
|
||||
if (flipflopContext.State == FfState.Cancel)
|
||||
{
|
||||
throw new Exception("this async task is cancel.");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (flipflopContext.State == FfState.Succeed)
|
||||
{
|
||||
FlowState = true;
|
||||
result = flipflopContext.Data;
|
||||
}
|
||||
else
|
||||
{
|
||||
FlowState = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
object?[]? parameters = GetParameters(context, MethodDetails);
|
||||
// 调用委托并获取结果
|
||||
FlipflopContext flipflopContext = await ((Func<object, object[], Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
|
||||
|
||||
if (flipflopContext != null)
|
||||
{
|
||||
if (flipflopContext.State == FfState.Cancel)
|
||||
{
|
||||
throw new Exception("取消此异步");
|
||||
}
|
||||
else
|
||||
{
|
||||
FlowState = flipflopContext.State == FfState.Succeed;
|
||||
result = flipflopContext.Data;
|
||||
}
|
||||
}
|
||||
}
|
||||
// context.SetFlowData(result);
|
||||
// CurrentData = result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public async Task ExecuteStack(DynamicContext context)
|
||||
{
|
||||
var cts = context.ServiceContainer.Get<CancellationTokenSource>();
|
||||
|
||||
Stack<NodeBase> stack =[];
|
||||
stack.Push(this);
|
||||
|
||||
while (stack.Count > 0 && !cts.IsCancellationRequested) // 循环中直到栈为空才会退出循环
|
||||
{
|
||||
|
||||
// 从栈中弹出一个节点作为当前节点进行处理
|
||||
var currentNode = stack.Pop();
|
||||
|
||||
//currentNode.MethodDetails.ActingInstance ??= context.ServiceContainer.Get(
|
||||
// currentNode.MethodDetails.ActingInstanceType
|
||||
// );
|
||||
|
||||
if (currentNode.MethodDetails != null)
|
||||
{
|
||||
currentNode.MethodDetails.ActingInstance ??= context.ServiceContainer.Get(MethodDetails.ActingInstanceType);
|
||||
}
|
||||
|
||||
if (currentNode.MethodDetails != null && currentNode.MethodDetails.MethodDynamicType == DynamicNodeType.Flipflop)
|
||||
{
|
||||
currentNode.FlowData = await currentNode.ExecuteAsync(context);
|
||||
}
|
||||
else
|
||||
{
|
||||
currentNode.FlowData = currentNode.Execute(context);
|
||||
}
|
||||
|
||||
|
||||
var nextNodes = currentNode.FlowState ? currentNode.TrueBranch
|
||||
: currentNode.FalseBranch;
|
||||
|
||||
// 将下一个节点集合中的所有节点逆序推入栈中
|
||||
for (int i = nextNodes.Count - 1; i >= 0; i--)
|
||||
{
|
||||
nextNodes[i].PreviousNode = currentNode;
|
||||
stack.Push(nextNodes[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public object[]? GetParameters(DynamicContext context, MethodDetails md)
|
||||
{
|
||||
// 用正确的大小初始化参数数组
|
||||
var types = md.ExplicitDatas.Select(it => it.DataType).ToArray();
|
||||
if (types.Length == 0)
|
||||
{
|
||||
return [md.ActingInstance];
|
||||
}
|
||||
|
||||
object[]? parameters = new object[types.Length];
|
||||
|
||||
for (int i = 0; i < types.Length; i++)
|
||||
{
|
||||
|
||||
var mdEd = md.ExplicitDatas[i];
|
||||
Type type = mdEd.DataType;
|
||||
if (type == typeof(DynamicContext))
|
||||
{
|
||||
parameters[i] = context;
|
||||
}
|
||||
else if (type == typeof(MethodDetails))
|
||||
{
|
||||
parameters[i] = md;
|
||||
}
|
||||
else if (type == typeof(NodeBase))
|
||||
{
|
||||
parameters[i] = this;
|
||||
}
|
||||
else if (mdEd.IsExplicitData) // 显式参数
|
||||
{
|
||||
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] = ConvertValue(mdEd.DataValue, mdEd.ExplicitType);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
//var tmpParameter = context.GetFlowData()?.ToString();
|
||||
var tmpParameter = PreviousNode?.FlowData?.ToString();
|
||||
if (mdEd.DataType.IsEnum)
|
||||
{
|
||||
var enumValue = Enum.Parse(mdEd.DataType, tmpParameter);
|
||||
parameters[i] = enumValue;
|
||||
}
|
||||
else if (mdEd.DataType == typeof(string))
|
||||
{
|
||||
parameters[i] = tmpParameter;
|
||||
}
|
||||
else if (mdEd.DataType == typeof(bool))
|
||||
{
|
||||
parameters[i] = bool.Parse(tmpParameter);
|
||||
}
|
||||
else if (mdEd.DataType == typeof(int))
|
||||
{
|
||||
parameters[i] = int.Parse(tmpParameter);
|
||||
}
|
||||
else if (mdEd.DataType == typeof(double))
|
||||
{
|
||||
parameters[i] = double.Parse(tmpParameter);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (tmpParameter != null && mdEd.DataType!= null)
|
||||
{
|
||||
parameters[i] = ConvertValue(tmpParameter, mdEd.DataType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
|
||||
private dynamic? ConvertValue(string value, Type targetType)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
{
|
||||
return JsonConvert.DeserializeObject(value, targetType);
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
catch (JsonReaderException ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
return value;
|
||||
}
|
||||
catch (JsonSerializationException ex)
|
||||
{
|
||||
// 如果无法转为对应的JSON对象
|
||||
int startIndex = ex.Message.IndexOf("to type '") + "to type '".Length; // 查找类型信息开始的索引
|
||||
int endIndex = ex.Message.IndexOf('\''); // 查找类型信息结束的索引
|
||||
var typeInfo = ex.Message[startIndex..endIndex]; // 提取出错类型信息,该怎么传出去?
|
||||
Console.WriteLine("无法转为对应的JSON对象:"+typeInfo);
|
||||
return null;
|
||||
}
|
||||
catch // (Exception ex)
|
||||
{
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#region 完整的ExecuteAsync调用方法(不要删除)
|
||||
//public virtual async Task<object?> ExecuteAsync(DynamicContext context)
|
||||
//{
|
||||
// MethodDetails md = MethodDetails;
|
||||
// object? result = null;
|
||||
// if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
|
||||
// {
|
||||
// if (md.ExplicitDatas.Length == 0)
|
||||
// {
|
||||
// if (md.ReturnType == typeof(void))
|
||||
// {
|
||||
// ((Action<object>)del).Invoke(md.ActingInstance);
|
||||
// }
|
||||
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
|
||||
// {
|
||||
// // 调用委托并获取结果
|
||||
// FlipflopContext flipflopContext = await ((Func<object, Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance);
|
||||
|
||||
// if (flipflopContext != null)
|
||||
// {
|
||||
// if (flipflopContext.State == FfState.Cancel)
|
||||
// {
|
||||
// throw new Exception("this async task is cancel.");
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// if (flipflopContext.State == FfState.Succeed)
|
||||
// {
|
||||
// CurrentState = true;
|
||||
// result = flipflopContext.Data;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// CurrentState = false;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// result = ((Func<object, object>)del).Invoke(md.ActingInstance);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// object?[]? parameters = GetParameters(context, MethodDetails);
|
||||
// if (md.ReturnType == typeof(void))
|
||||
// {
|
||||
// ((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
|
||||
// }
|
||||
// else if (md.ReturnType == typeof(Task<FlipflopContext>))
|
||||
// {
|
||||
// // 调用委托并获取结果
|
||||
// FlipflopContext flipflopContext = await ((Func<object, object[], Task<FlipflopContext>>)del).Invoke(MethodDetails.ActingInstance, parameters);
|
||||
|
||||
// if (flipflopContext != null)
|
||||
// {
|
||||
// if (flipflopContext.State == FfState.Cancel)
|
||||
// {
|
||||
// throw new Exception("取消此异步");
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// CurrentState = flipflopContext.State == FfState.Succeed;
|
||||
// result = flipflopContext.Data;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
|
||||
// }
|
||||
// }
|
||||
// context.SetFlowData(result);
|
||||
// }
|
||||
// return result;
|
||||
//}
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/* while (stack.Count > 0) // 循环中直到栈为空才会退出
|
||||
{
|
||||
// 从栈中弹出一个节点作为当前节点进行处理
|
||||
var currentNode = stack.Pop();
|
||||
|
||||
if(currentNode is CompositeActionNode || currentNode is CompositeConditionNode)
|
||||
{
|
||||
currentNode.currentState = true;
|
||||
}
|
||||
else if (currentNode is CompositeConditionNode)
|
||||
{
|
||||
|
||||
}
|
||||
currentNode.Execute(context);
|
||||
// 根据当前节点的执行结果选择下一节点集合
|
||||
// 如果 currentState 为真,选择 TrueBranchNextNodes;否则选择 FalseBranchNextNodes
|
||||
var nextNodes = currentNode.currentState ? currentNode.TrueBranchNextNodes
|
||||
: currentNode.FalseBranchNextNodes;
|
||||
|
||||
// 将下一个节点集合中的所有节点逆序推入栈中
|
||||
for (int i = nextNodes.Count - 1; i >= 0; i--)
|
||||
{
|
||||
stack.Push(nextNodes[i]);
|
||||
}
|
||||
|
||||
}*/
|
||||
71
Library/DynamicFlow/NodeModel/SingleActionNode.cs
Normal file
71
Library/DynamicFlow/NodeModel/SingleActionNode.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using Serein.DynamicFlow.Tool;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 单动作节点(用于动作控件)
|
||||
/// </summary>
|
||||
public class SingleActionNode : NodeBase
|
||||
{
|
||||
//public override void Execute(DynamicContext context)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// Execute(context, base.MethodDetails);
|
||||
// CurrentState = true;
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// Debug.Write(ex.Message);
|
||||
// CurrentState = false;
|
||||
// }
|
||||
//}
|
||||
|
||||
//public void Execute(DynamicContext context, MethodDetails md)
|
||||
//{
|
||||
// if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
|
||||
// {
|
||||
|
||||
// object? result = null;
|
||||
|
||||
// if (md.ExplicitDatas.Length == 0)
|
||||
// {
|
||||
// if (md.ReturnType == typeof(void))
|
||||
// {
|
||||
// ((Action<object>)del).Invoke(md.ActingInstance);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// result = ((Func<object, object>)del).Invoke(md.ActingInstance);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// object?[]? parameters = GetParameters(context, MethodDetails);
|
||||
// if (md.ReturnType == typeof(void))
|
||||
// {
|
||||
// ((Action<object, object[]>)del).Invoke(md.ActingInstance, parameters);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// result = ((Func<object, object[], object>)del).Invoke(md.ActingInstance, parameters);
|
||||
// }
|
||||
// }
|
||||
|
||||
// // 根据 ExplicitDatas.Length 判断委托类型
|
||||
// //var action = (Action<object, object[]>)del;
|
||||
|
||||
// // 调用委托并获取结果
|
||||
// // action.Invoke(MethodDetails.ActingInstance, parameters);
|
||||
|
||||
// //parameters = [md.ActingInstance, "", 123, ""];
|
||||
|
||||
// context.SetFlowData(result);
|
||||
// }
|
||||
//}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
72
Library/DynamicFlow/NodeModel/SingleConditionNode.cs
Normal file
72
Library/DynamicFlow/NodeModel/SingleConditionNode.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using Serein.DynamicFlow.SerinExpression;
|
||||
using Serein.DynamicFlow.Tool;
|
||||
using System.Diagnostics;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
/// <summary>
|
||||
/// 条件节点(用于条件控件)
|
||||
/// </summary>
|
||||
public class SingleConditionNode : NodeBase
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 是否为自定义参数
|
||||
/// </summary>
|
||||
public bool IsCustomData { get; set; }
|
||||
/// <summary>
|
||||
/// 自定义参数值
|
||||
/// </summary>
|
||||
public object? CustomData { get; set; }
|
||||
/// <summary>
|
||||
/// 条件表达式
|
||||
/// </summary>
|
||||
public string Expression { get; set; }
|
||||
|
||||
public override object? Execute(DynamicContext context)
|
||||
{
|
||||
// 接收上一节点参数or自定义参数内容
|
||||
object? result;
|
||||
if (IsCustomData)
|
||||
{
|
||||
result = CustomData;
|
||||
}
|
||||
else
|
||||
{
|
||||
result = PreviousNode?.FlowData;
|
||||
}
|
||||
FlowState = SerinConditionParser.To(result, Expression);
|
||||
Console.WriteLine($"{result} {Expression} -> " + FlowState);
|
||||
return result;
|
||||
}
|
||||
|
||||
//public override void Execute(DynamicContext context)
|
||||
//{
|
||||
// CurrentState = Judge(context, base.MethodDetails);
|
||||
//}
|
||||
|
||||
//private bool Judge(DynamicContext context, MethodDetails md)
|
||||
//{
|
||||
// try
|
||||
// {
|
||||
// if (DelegateCache.GlobalDicDelegates.TryGetValue(md.MethodName, out Delegate del))
|
||||
// {
|
||||
// object[] parameters = GetParameters(context, md);
|
||||
// var temp = del.DynamicInvoke(parameters);
|
||||
// //context.GetData(GetDyPreviousKey());
|
||||
// return (bool)temp;
|
||||
// }
|
||||
// }
|
||||
// catch (Exception ex)
|
||||
// {
|
||||
// Debug.Write(ex.Message);
|
||||
// }
|
||||
// return false;
|
||||
//}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
44
Library/DynamicFlow/NodeModel/SingleExpOpNode.cs
Normal file
44
Library/DynamicFlow/NodeModel/SingleExpOpNode.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using Serein.DynamicFlow.SerinExpression;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
/// <summary>
|
||||
/// Expression Operation - 表达式操作
|
||||
/// </summary>
|
||||
public class SingleExpOpNode : NodeBase
|
||||
{
|
||||
public string Expression { get; set; }
|
||||
|
||||
|
||||
public override object? Execute(DynamicContext context)
|
||||
{
|
||||
//if (PreviousNode != null && PreviousNode.FlowData == null)
|
||||
//{
|
||||
// // 存在
|
||||
// throw new InvalidOperationException("previous node data is null.");
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
|
||||
//}
|
||||
var data = PreviousNode?.FlowData;
|
||||
var newData = SerinExpressionEvaluator.Evaluate(Expression, data, out bool isChange);
|
||||
FlowState = true;
|
||||
Console.WriteLine(newData);
|
||||
if (isChange)
|
||||
{
|
||||
return newData;
|
||||
}
|
||||
else
|
||||
{
|
||||
return PreviousNode?.FlowData;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
40
Library/DynamicFlow/NodeModel/SingleFlipflopNode.cs
Normal file
40
Library/DynamicFlow/NodeModel/SingleFlipflopNode.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using Serein.DynamicFlow.Tool;
|
||||
|
||||
namespace Serein.DynamicFlow.NodeModel
|
||||
{
|
||||
|
||||
public class SingleFlipflopNode : NodeBase
|
||||
{
|
||||
//public override void Execute(DynamicContext context)
|
||||
//{
|
||||
// throw new NotImplementedException("无法以非await/async的形式调用触发器");
|
||||
//}
|
||||
|
||||
//public virtual async Task ExecuteAsync(DynamicContext context, Action NextTask = null)
|
||||
//{
|
||||
// if (DelegateCache.GlobalDicDelegates.TryGetValue(MethodDetails.MethodName, out Delegate? del))
|
||||
// {
|
||||
// object?[]? parameters = GetParameters(context, MethodDetails);
|
||||
|
||||
// // 根据 ExplicitDatas.Length 判断委托类型
|
||||
// var func = (Func<object, object[], Task<FlipflopContext>>)del;
|
||||
|
||||
// // 调用委托并获取结果
|
||||
// FlipflopContext flipflopContext = await func.Invoke(MethodDetails.ActingInstance, parameters);
|
||||
|
||||
// if (flipflopContext != null)
|
||||
// {
|
||||
// if (flipflopContext.State == FfState.Cancel)
|
||||
// {
|
||||
// throw new Exception("取消此异步");
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// CurrentState = flipflopContext.State == FfState.Succeed;
|
||||
// context.SetFlowData(flipflopContext.Data);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
||||
320
Library/DynamicFlow/SerinExpression/ConditionResolver.cs
Normal file
320
Library/DynamicFlow/SerinExpression/ConditionResolver.cs
Normal file
@@ -0,0 +1,320 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Serein.DynamicFlow.SerinExpression
|
||||
{
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
318
Library/DynamicFlow/SerinExpression/SerinConditionParser.cs
Normal file
318
Library/DynamicFlow/SerinExpression/SerinConditionParser.cs
Normal file
@@ -0,0 +1,318 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Serein.DynamicFlow.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('.') /*&& expression.Contains('<') && expression.Contains('>')*/)
|
||||
{
|
||||
return ParseObjectExpression(data, expression);
|
||||
}
|
||||
else
|
||||
{
|
||||
return ParseSimpleExpression(data, expression);
|
||||
}
|
||||
|
||||
bool ContainsArithmeticOperators(string expression)
|
||||
{
|
||||
return expression.Contains('+') || expression.Contains('-') || expression.Contains('*') || expression.Contains('/');
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
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 = (tempType ?? Type.GetType(typeStr)) ?? 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.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.")
|
||||
};
|
||||
}
|
||||
}
|
||||
196
Library/DynamicFlow/SerinExpression/SerinExpressionEvaluator.cs
Normal file
196
Library/DynamicFlow/SerinExpression/SerinExpressionEvaluator.cs
Normal file
@@ -0,0 +1,196 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static Serein.DynamicFlow.NodeModel.SingleExpOpNode;
|
||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||
|
||||
namespace Serein.DynamicFlow.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
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
186
Library/DynamicFlow/Tool/DelegateGenerator.cs
Normal file
186
Library/DynamicFlow/Tool/DelegateGenerator.cs
Normal file
@@ -0,0 +1,186 @@
|
||||
using Serein;
|
||||
using Serein.DynamicFlow;
|
||||
using Serein.DynamicFlow.NodeModel;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Serein.DynamicFlow.Tool;
|
||||
|
||||
|
||||
public static class DelegateCache
|
||||
{
|
||||
/// <summary>
|
||||
/// 委托缓存全局字典
|
||||
/// </summary>
|
||||
public static ConcurrentDictionary<string, Delegate> GlobalDicDelegates { get; } = new ConcurrentDictionary<string, Delegate>();
|
||||
}
|
||||
|
||||
public static class DelegateGenerator
|
||||
{
|
||||
// 缓存的实例对象(键:类型名称)
|
||||
public static ConcurrentDictionary<string, object> DynamicInstanceToType { get; } = new ConcurrentDictionary<string, object>();
|
||||
// 缓存的实例对象 (键:生成的方法名称)
|
||||
// public static ConcurrentDictionary<string, object> DynamicInstance { get; } = new ConcurrentDictionary<string, object>();
|
||||
|
||||
/// <summary>
|
||||
/// 生成方法信息
|
||||
/// </summary>
|
||||
/// <param name="serviceContainer"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <returns></returns>
|
||||
public static ConcurrentDictionary<string, MethodDetails> GenerateMethodDetails(IServiceContainer serviceContainer, Type type)
|
||||
{
|
||||
var methodDetailsDictionary = new ConcurrentDictionary<string, MethodDetails>();
|
||||
var assemblyName = type.Assembly.GetName().Name;
|
||||
var methods = GetMethodsToProcess(type);
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var methodDetails = CreateMethodDetails(serviceContainer, type, method, assemblyName);
|
||||
methodDetailsDictionary.TryAdd(methodDetails.MethodName, methodDetails);
|
||||
}
|
||||
|
||||
return methodDetailsDictionary;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取处理方法
|
||||
/// </summary>
|
||||
private static IEnumerable<MethodInfo> GetMethodsToProcess(Type type)
|
||||
{
|
||||
return type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
|
||||
.Where(m => m.GetCustomAttribute<MethodDetailAttribute>()?.Scan == true);
|
||||
}
|
||||
/// <summary>
|
||||
/// 创建方法信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static MethodDetails CreateMethodDetails(IServiceContainer serviceContainer, Type type, MethodInfo method, string assemblyName)
|
||||
{
|
||||
var methodName = method.Name;
|
||||
var attribute = method.GetCustomAttribute<MethodDetailAttribute>();
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
private static ExplicitData[] GetExplicitDataOfParameters(ParameterInfo[] parameters)
|
||||
{
|
||||
|
||||
return parameters.Select((it, index) =>
|
||||
{
|
||||
//Console.WriteLine($"{it.Name}-{it.HasDefaultValue}-{it.DefaultValue}");
|
||||
string explicitTypeName = GetExplicitTypeName(it.ParameterType);
|
||||
var items = GetExplicitItems(it.ParameterType, explicitTypeName);
|
||||
if ("Bool".Equals(explicitTypeName)) explicitTypeName = "Select"; // 布尔值 转为 可选类型
|
||||
return new ExplicitData
|
||||
{
|
||||
IsExplicitData = it.GetCustomAttribute(typeof(ExplicitAttribute)) is ExplicitAttribute,
|
||||
Index = index,
|
||||
ExplicitType = it.ParameterType,
|
||||
ExplicitTypeName = explicitTypeName,
|
||||
DataType = it.ParameterType,
|
||||
ParameterName = it.Name,
|
||||
DataValue = it.HasDefaultValue ? it.DefaultValue.ToString() : "",
|
||||
Items = items.ToArray(),
|
||||
};
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
private static string GetExplicitTypeName(Type type)
|
||||
{
|
||||
return type switch
|
||||
{
|
||||
Type t when t.IsEnum => "Select",
|
||||
Type t when t == typeof(bool) => "Bool",
|
||||
Type t when t == typeof(string) => "Value",
|
||||
Type t when t == typeof(int) => "Value",
|
||||
Type t when t == typeof(double) => "Value",
|
||||
_ => "Value"
|
||||
};
|
||||
}
|
||||
|
||||
private static IEnumerable<string> GetExplicitItems(Type type, string explicitTypeName)
|
||||
{
|
||||
return explicitTypeName switch
|
||||
{
|
||||
"Select" => Enum.GetNames(type),
|
||||
"Bool" => ["True", "False"],
|
||||
_ => []
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
private static Delegate GenerateMethodDelegate(Type type, MethodInfo methodInfo, ParameterInfo[] parameters, Type returnType)
|
||||
{
|
||||
var parameterTypes = parameters.Select(p => p.ParameterType).ToArray();
|
||||
var parameterCount = parameters.Length;
|
||||
|
||||
if (returnType == typeof(void))
|
||||
{
|
||||
if (parameterCount == 0)
|
||||
{
|
||||
// 无返回值,无参数
|
||||
return ExpressionHelper.MethodCaller(type, methodInfo);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 无返回值,有参数
|
||||
return ExpressionHelper.MethodCaller(type, methodInfo, parameterTypes);
|
||||
}
|
||||
}
|
||||
else if (returnType == typeof(Task<FlipflopContext>)) // 触发器
|
||||
{
|
||||
if (parameterCount == 0)
|
||||
{
|
||||
// 有返回值,无参数
|
||||
return ExpressionHelper.MethodCallerAsync(type, methodInfo);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 有返回值,有参数
|
||||
return ExpressionHelper.MethodCallerAsync(type, methodInfo, parameterTypes);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (parameterCount == 0)
|
||||
{
|
||||
// 有返回值,无参数
|
||||
return ExpressionHelper.MethodCallerHaveResult(type, methodInfo);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 有返回值,有参数
|
||||
return ExpressionHelper.MethodCallerHaveResult(type, methodInfo, parameterTypes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
203
Library/DynamicFlow/Tool/DynamicTool.cs
Normal file
203
Library/DynamicFlow/Tool/DynamicTool.cs
Normal file
@@ -0,0 +1,203 @@
|
||||
using Serein;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing.Printing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.DynamicFlow.Tool
|
||||
{
|
||||
|
||||
#region 锁、tsk工具 (已注释)
|
||||
/*public class LockManager
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, LockQueue> _locks = new ConcurrentDictionary<string, LockQueue>();
|
||||
|
||||
public void CreateLock(string name)
|
||||
{
|
||||
_locks.TryAdd(name, new LockQueue());
|
||||
}
|
||||
|
||||
public async Task AcquireLockAsync(string name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_locks.ContainsKey(name))
|
||||
{
|
||||
throw new ArgumentException($"Lock with name '{name}' does not exist.");
|
||||
}
|
||||
|
||||
var lockQueue = _locks[name];
|
||||
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
lock (lockQueue.Queue)
|
||||
{
|
||||
lockQueue.Queue.Enqueue(tcs);
|
||||
if (lockQueue.Queue.Count == 1)
|
||||
{
|
||||
tcs.SetResult(true);
|
||||
}
|
||||
}
|
||||
|
||||
await tcs.Task.ConfigureAwait(false);
|
||||
|
||||
// 处理取消操作
|
||||
if (cancellationToken.CanBeCanceled)
|
||||
{
|
||||
cancellationToken.Register(() =>
|
||||
{
|
||||
lock (lockQueue.Queue)
|
||||
{
|
||||
if (lockQueue.Queue.Contains(tcs))
|
||||
{
|
||||
tcs.TrySetCanceled();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void ReleaseLock(string name)
|
||||
{
|
||||
if (!_locks.ContainsKey(name))
|
||||
{
|
||||
throw new ArgumentException($"Lock with name '{name}' does not exist.");
|
||||
}
|
||||
|
||||
var lockQueue = _locks[name];
|
||||
|
||||
lock (lockQueue.Queue)
|
||||
{
|
||||
if (lockQueue.Queue.Count > 0)
|
||||
{
|
||||
lockQueue.Queue.Dequeue();
|
||||
|
||||
if (lockQueue.Queue.Count > 0)
|
||||
{
|
||||
var next = lockQueue.Queue.Peek();
|
||||
next.SetResult(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class LockQueue
|
||||
{
|
||||
public Queue<TaskCompletionSource<bool>> Queue { get; } = new Queue<TaskCompletionSource<bool>>();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public interface ITaskResult
|
||||
{
|
||||
object Result { get; }
|
||||
}
|
||||
|
||||
public class TaskResult<T> : ITaskResult
|
||||
{
|
||||
public TaskResult(T result)
|
||||
{
|
||||
Result = result;
|
||||
}
|
||||
|
||||
public T Result { get; }
|
||||
|
||||
object ITaskResult.Result => Result;
|
||||
}
|
||||
|
||||
public class DynamicTasks
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, Task<ITaskResult>> TaskGuidPairs = new();
|
||||
public static Task<ITaskResult> GetTask(string Guid)
|
||||
{
|
||||
TaskGuidPairs.TryGetValue(Guid, out Task<ITaskResult> task);
|
||||
return task;
|
||||
}
|
||||
|
||||
public static bool AddTask<T>(string Guid, T result)
|
||||
{
|
||||
var task = Task.FromResult<ITaskResult>(new TaskResult<T>(result));
|
||||
|
||||
return TaskGuidPairs.TryAdd(Guid, task);
|
||||
}
|
||||
}
|
||||
public class TaskNodeManager
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, TaskQueue> _taskQueues = new ConcurrentDictionary<string, TaskQueue>();
|
||||
|
||||
public void CreateTaskNode(string name)
|
||||
{
|
||||
_taskQueues.TryAdd(name, new TaskQueue());
|
||||
}
|
||||
|
||||
public async Task WaitForTaskNodeAsync(string name, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_taskQueues.ContainsKey(name))
|
||||
{
|
||||
throw new ArgumentException($"Task node with name '{name}' does not exist.");
|
||||
}
|
||||
|
||||
var taskQueue = _taskQueues[name];
|
||||
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
lock (taskQueue.Queue)
|
||||
{
|
||||
taskQueue.Queue.Enqueue(tcs);
|
||||
if (taskQueue.Queue.Count == 1)
|
||||
{
|
||||
tcs.SetResult(true);
|
||||
}
|
||||
}
|
||||
|
||||
await tcs.Task.ConfigureAwait(false);
|
||||
|
||||
// 处理取消操作
|
||||
if (cancellationToken.CanBeCanceled)
|
||||
{
|
||||
cancellationToken.Register(() =>
|
||||
{
|
||||
lock (taskQueue.Queue)
|
||||
{
|
||||
if (taskQueue.Queue.Contains(tcs))
|
||||
{
|
||||
tcs.TrySetCanceled();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void CompleteTaskNode(string name)
|
||||
{
|
||||
if (!_taskQueues.ContainsKey(name))
|
||||
{
|
||||
throw new ArgumentException($"Task node with name '{name}' does not exist.");
|
||||
}
|
||||
|
||||
var taskQueue = _taskQueues[name];
|
||||
|
||||
lock (taskQueue.Queue)
|
||||
{
|
||||
if (taskQueue.Queue.Count > 0)
|
||||
{
|
||||
taskQueue.Queue.Dequeue();
|
||||
|
||||
if (taskQueue.Queue.Count > 0)
|
||||
{
|
||||
var next = taskQueue.Queue.Peek();
|
||||
next.SetResult(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class TaskQueue
|
||||
{
|
||||
public Queue<TaskCompletionSource<bool>> Queue { get; } = new Queue<TaskCompletionSource<bool>>();
|
||||
}
|
||||
}*/
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
}
|
||||
740
Library/DynamicFlow/Tool/ExpressionHelper.cs
Normal file
740
Library/DynamicFlow/Tool/ExpressionHelper.cs
Normal file
@@ -0,0 +1,740 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Serein.DynamicFlow.Tool
|
||||
{
|
||||
/// <summary>
|
||||
/// 对于实例创建的表达式树反射
|
||||
/// </summary>
|
||||
public static class ExpressionHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 缓存表达式树反射方法
|
||||
/// </summary>
|
||||
private static ConcurrentDictionary<string, Delegate> Cache { get; } = new ConcurrentDictionary<string, Delegate>();
|
||||
|
||||
public static List<string> GetCacheKey()
|
||||
{
|
||||
return [.. Cache.Keys];
|
||||
}
|
||||
|
||||
#region 基于类型的表达式反射构建委托
|
||||
|
||||
#region 属性、字段的委托创建(表达式反射)
|
||||
|
||||
/// <summary>
|
||||
/// 动态获取属性值
|
||||
/// </summary>
|
||||
public static Delegate PropertyGetter(Type type, string propertyName)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{propertyName}.Getter";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateGetterDelegate(type, propertyName));
|
||||
}
|
||||
/// <summary>
|
||||
/// 动态获取属性值
|
||||
/// </summary>
|
||||
private static Delegate CreateGetterDelegate(Type type, string propertyName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var property = Expression.Property(Expression.Convert(parameter, type), propertyName);
|
||||
var lambda = Expression.Lambda(Expression.Convert(property, typeof(object)), parameter);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态设置属性值
|
||||
/// </summary>
|
||||
public static Delegate PropertySetter(Type type, string propertyName)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{propertyName}.Setter";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateSetterDelegate(type, propertyName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态设置属性值
|
||||
/// </summary>
|
||||
private static Delegate CreateSetterDelegate(Type type, string propertyName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var value = Expression.Parameter(typeof(object), "value");
|
||||
var property = Expression.Property(Expression.Convert(parameter, type), propertyName);
|
||||
var assign = Expression.Assign(property, Expression.Convert(value, property.Type));
|
||||
var lambda = Expression.Lambda(assign, parameter, value);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态获取字段值
|
||||
/// </summary>
|
||||
public static Delegate FieldGetter(Type type, string fieldName)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{fieldName}.FieldGetter";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateFieldGetterDelegate(type, fieldName));
|
||||
}
|
||||
/// <summary>
|
||||
/// 动态获取字段值
|
||||
/// </summary>
|
||||
private static Delegate CreateFieldGetterDelegate(Type type, string fieldName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var field = Expression.Field(Expression.Convert(parameter, type), fieldName);
|
||||
var lambda = Expression.Lambda(Expression.Convert(field, typeof(object)), parameter);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态设置字段值
|
||||
/// </summary>
|
||||
public static Delegate FieldSetter(Type type, string fieldName)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{fieldName}.FieldSetter";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateFieldSetterDelegate(type, fieldName));
|
||||
}
|
||||
/// <summary>
|
||||
/// 动态设置字段值
|
||||
/// </summary>
|
||||
private static Delegate CreateFieldSetterDelegate(Type type, string fieldName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var value = Expression.Parameter(typeof(object), "value");
|
||||
var field = Expression.Field(Expression.Convert(parameter, type), fieldName);
|
||||
var assign = Expression.Assign(field, Expression.Convert(value, field.Type));
|
||||
var lambda = Expression.Lambda(assign, parameter, value);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建无参数,无返回值方法
|
||||
/// </summary>
|
||||
public static Delegate MethodCaller(Type type, MethodInfo methodInfo)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodInfo.Name}.MethodCaller";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate(type, methodInfo));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建无参数,无返回值方法
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegate(Type type, MethodInfo methodInfo)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type), methodInfo);
|
||||
var lambda = Expression.Lambda(methodCall, parameter);
|
||||
// Action<object>
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建无参数,有返回值方法
|
||||
/// </summary>
|
||||
public static Delegate MethodCallerHaveResult(Type type, MethodInfo methodInfo)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodInfo.Name}.MethodCallerHaveResult";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateHaveResult(type, methodInfo));
|
||||
}
|
||||
/// <summary>
|
||||
/// 表达式树构建无参数,有返回值方法
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegateHaveResult(Type type, MethodInfo methodInfo)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type), methodInfo);
|
||||
var lambda = Expression.Lambda(Expression.Convert(methodCall, typeof(object)), parameter);
|
||||
// Func<object, object>
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建多个参数,无返回值的方法
|
||||
/// </summary>
|
||||
public static Delegate MethodCaller(Type type, MethodInfo methodInfo, params Type[] parameterTypes)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodInfo.Name}.MethodCaller";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate(type, methodInfo, parameterTypes));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建多个参数,无返回值的方法
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegate(Type type, MethodInfo methodInfo, Type[] parameterTypes)
|
||||
{
|
||||
/* var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
|
||||
var arguments = parameterTypes.Select((t, i) => Expression.Parameter(typeof(object), $"arg{i}")).ToArray();
|
||||
|
||||
var convertedArguments = arguments.Select((arg, i) => Expression.Convert(arg, parameterTypes[i])).ToArray();
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type),
|
||||
methodInfo,
|
||||
convertedArguments);
|
||||
var lambda = Expression.Lambda(methodCall, new[] { parameter }.Concat(arguments));
|
||||
var tmpAction = lambda.Compile();
|
||||
|
||||
// Action<object, object[]>
|
||||
return lambda.Compile();*/
|
||||
|
||||
var instanceParam = Expression.Parameter(typeof(object), "instance");
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
|
||||
// 创建参数表达式
|
||||
var convertedArgs = parameterTypes.Select((paramType, index) =>
|
||||
Expression.Convert(Expression.ArrayIndex(argsParam, Expression.Constant(index)), paramType)
|
||||
).ToArray();
|
||||
|
||||
|
||||
// 创建方法调用表达式
|
||||
var methodCall = Expression.Call(
|
||||
Expression.Convert(instanceParam, type),
|
||||
methodInfo,
|
||||
(Expression[])convertedArgs
|
||||
);
|
||||
|
||||
// 创建 lambda 表达式
|
||||
var lambda = Expression.Lambda(
|
||||
methodCall,
|
||||
instanceParam,
|
||||
argsParam
|
||||
);
|
||||
|
||||
// Func<object, object[], object>
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建多个参数,有返回值的方法
|
||||
/// </summary>
|
||||
public static Delegate MethodCallerHaveResult(Type type, MethodInfo methodInfo, Type[] parameterTypes)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodInfo.Name}.MethodCallerHaveResult";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateHaveResult(type, methodInfo, parameterTypes));
|
||||
}
|
||||
/// <summary>
|
||||
/// 表达式树构建多个参数,有返回值的方法
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegateHaveResult(Type type, MethodInfo methodInfo, Type[] parameterTypes)
|
||||
{
|
||||
/*var instanceParam = Expression.Parameter(typeof(object), "instance");
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
|
||||
// 创建参数表达式
|
||||
var convertedArgs = parameterTypes.Select((paramType, index) =>
|
||||
Expression.Convert(Expression.ArrayIndex(argsParam, Expression.Constant(index)), paramType)
|
||||
).ToArray();
|
||||
|
||||
|
||||
// 创建方法调用表达式
|
||||
var methodCall = Expression.Call(
|
||||
Expression.Convert(instanceParam, type),
|
||||
methodInfo,
|
||||
convertedArgs
|
||||
);
|
||||
|
||||
// 创建 lambda 表达式
|
||||
var lambda = Expression.Lambda(
|
||||
Expression.Convert(methodCall, typeof(object)),
|
||||
instanceParam,
|
||||
argsParam
|
||||
);
|
||||
|
||||
// Func<object, object[], object>
|
||||
return lambda.Compile();*/
|
||||
|
||||
var instanceParam = Expression.Parameter(typeof(object), "instance");
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
|
||||
// 创建参数表达式
|
||||
var convertedArgs = parameterTypes.Select((paramType, index) =>
|
||||
Expression.Convert(Expression.ArrayIndex(argsParam, Expression.Constant(index)), paramType)
|
||||
).ToArray();
|
||||
|
||||
|
||||
// 创建方法调用表达式
|
||||
var methodCall = Expression.Call(
|
||||
Expression.Convert(instanceParam, type),
|
||||
methodInfo,
|
||||
convertedArgs
|
||||
);
|
||||
|
||||
// 创建 lambda 表达式
|
||||
var lambda = Expression.Lambda<Func<object, object[], object>>(
|
||||
Expression.Convert(methodCall, typeof(object)),
|
||||
instanceParam,
|
||||
argsParam
|
||||
);
|
||||
//var resule = task.DynamicInvoke((object)[Activator.CreateInstance(type), [new DynamicContext(null)]]);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建无参数,有返回值(Task<object>)的方法(触发器)
|
||||
/// </summary>
|
||||
public static Delegate MethodCallerAsync(Type type, MethodInfo methodInfo)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodInfo.Name}.MethodCallerAsync";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateAsync(type, methodInfo));
|
||||
}
|
||||
/// <summary>
|
||||
/// 表达式树构建无参数,有返回值(Task<object>)的方法(触发器)
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegateAsync(Type type, MethodInfo methodInfo)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type), methodInfo);
|
||||
var lambda = Expression.Lambda<Func<object, Task<object>>>(
|
||||
Expression.Convert(methodCall, typeof(Task<object>)), parameter);
|
||||
// Func<object, Task<object>>
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建多个参数,有返回值(Task-object)的方法(触发器)
|
||||
/// </summary>
|
||||
public static Delegate MethodCallerAsync(Type type, MethodInfo method, params Type[] parameterTypes)
|
||||
{
|
||||
|
||||
string cacheKey = $"{type.FullName}.{method.Name}.MethodCallerAsync";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateAsync(type, method, parameterTypes));
|
||||
}
|
||||
/// <summary>
|
||||
/// 表达式树构建多个参数,有返回值(Task<object>)的方法(触发器)
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegateAsync(Type type, MethodInfo methodInfo, Type[] parameterTypes)
|
||||
{
|
||||
var instanceParam = Expression.Parameter(typeof(object), "instance");
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
|
||||
// 创建参数表达式
|
||||
var convertedArgs = parameterTypes.Select((paramType, index) =>
|
||||
Expression.Convert(Expression.ArrayIndex(argsParam, Expression.Constant(index)),paramType)
|
||||
).ToArray();
|
||||
|
||||
|
||||
// 创建方法调用表达式
|
||||
var methodCall = Expression.Call(
|
||||
Expression.Convert(instanceParam, type),
|
||||
methodInfo,
|
||||
(Expression[])convertedArgs
|
||||
);
|
||||
|
||||
// 创建 lambda 表达式
|
||||
var lambda = Expression.Lambda<Func<object, object[], Task<FlipflopContext>>>(
|
||||
Expression.Convert(methodCall, typeof(Task<FlipflopContext>)),
|
||||
instanceParam,
|
||||
argsParam
|
||||
);
|
||||
//var resule = task.DynamicInvoke((object)[Activator.CreateInstance(type), [new DynamicContext(null)]]);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
|
||||
#region 单参数
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建单参数,无返回值的方法
|
||||
/// </summary>
|
||||
public static Delegate MethodCaller(Type type, string methodName, Type parameterType)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodName}.MethodCallerWithParam";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate(type, methodName, parameterType));
|
||||
}
|
||||
/// <summary>
|
||||
/// 表达式树构建单参数,无返回值的方法
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegate(Type type, string methodName, Type parameterType)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var argument = Expression.Parameter(typeof(object), "argument");
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type),
|
||||
type.GetMethod(methodName, [parameterType])!,
|
||||
Expression.Convert(argument, parameterType));
|
||||
var lambda = Expression.Lambda(methodCall, parameter, argument);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表达式树构建单参数,有返回值的方法
|
||||
/// </summary>
|
||||
public static Delegate MethodCallerWithResult(Type type, string methodName, Type parameterType, Type returnType)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodName}.MethodCallerWithResult";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateWithResult(type, methodName, parameterType, returnType));
|
||||
}
|
||||
/// <summary>
|
||||
/// 表达式树构建单参数,有返回值的方法
|
||||
/// </summary>
|
||||
private static Delegate CreateMethodCallerDelegateWithResult(Type type, string methodName, Type parameterType, Type returnType)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var argument = Expression.Parameter(typeof(object), "argument");
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type),
|
||||
type.GetMethod(methodName, [parameterType])!,
|
||||
Expression.Convert(argument, parameterType));
|
||||
var lambda = Expression.Lambda(Expression.Convert(methodCall, typeof(object)), parameter, argument);
|
||||
|
||||
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region 泛型表达式反射构建方法(已注释)
|
||||
/*
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 动态获取属性值
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TProperty"></typeparam>
|
||||
/// <param name="propertyName"></param>
|
||||
/// <returns></returns>
|
||||
public static Func<T, TProperty> PropertyGetter<T, TProperty>(string propertyName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{propertyName}.Getter";
|
||||
return (Func<T, TProperty>)Cache.GetOrAdd(cacheKey, _ => CreateGetterDelegate<T, TProperty>(propertyName));
|
||||
}
|
||||
|
||||
private static Func<T, TProperty> CreateGetterDelegate<T, TProperty>(string propertyName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var property = Expression.Property(parameter, propertyName);
|
||||
var lambda = Expression.Lambda<Func<T, TProperty>>(property, parameter);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态设置属性值
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TProperty"></typeparam>
|
||||
/// <param name="propertyName"></param>
|
||||
/// <returns></returns>
|
||||
public static Action<T, TProperty> PropertySetter<T, TProperty>(string propertyName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{propertyName}.Setter";
|
||||
return (Action<T, TProperty>)Cache.GetOrAdd(cacheKey, _ => CreateSetterDelegate<T, TProperty>(propertyName));
|
||||
}
|
||||
|
||||
private static Action<T, TProperty> CreateSetterDelegate<T, TProperty>(string propertyName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var value = Expression.Parameter(typeof(TProperty), "value");
|
||||
var property = Expression.Property(parameter, propertyName);
|
||||
var assign = Expression.Assign(property, value);
|
||||
var lambda = Expression.Lambda<Action<T, TProperty>>(assign, parameter, value);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态获取字段值
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TField"></typeparam>
|
||||
/// <param name="fieldName"></param>
|
||||
/// <returns></returns>
|
||||
public static Func<T, TField> FieldGetter<T, TField>(string fieldName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{fieldName}.FieldGetter";
|
||||
return (Func<T, TField>)Cache.GetOrAdd(cacheKey, _ => CreateFieldGetterDelegate<T, TField>(fieldName));
|
||||
}
|
||||
|
||||
private static Func<T, TField> CreateFieldGetterDelegate<T, TField>(string fieldName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var field = Expression.Field(parameter, fieldName);
|
||||
var lambda = Expression.Lambda<Func<T, TField>>(field, parameter);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态设置字段值
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TField"></typeparam>
|
||||
/// <param name="fieldName"></param>
|
||||
/// <returns></returns>
|
||||
public static Action<T, TField> FieldSetter<T, TField>(string fieldName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{fieldName}.FieldSetter";
|
||||
return (Action<T, TField>)Cache.GetOrAdd(cacheKey, _ => CreateFieldSetterDelegate<T, TField>(fieldName));
|
||||
}
|
||||
|
||||
private static Action<T, TField> CreateFieldSetterDelegate<T, TField>(string fieldName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var value = Expression.Parameter(typeof(TField), "value");
|
||||
var field = Expression.Field(parameter, fieldName);
|
||||
var assign = Expression.Assign(field, value);
|
||||
var lambda = Expression.Lambda<Action<T, TField>>(assign, parameter, value);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 动态调用无参数方法
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="methodName"></param>
|
||||
/// <returns></returns>
|
||||
public static Action<T> MethodCaller<T>(string methodName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{methodName}.MethodCaller";
|
||||
return (Action<T>)Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate<T>(methodName));
|
||||
}
|
||||
|
||||
private static Action<T> CreateMethodCallerDelegate<T>(string methodName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var methodCall = Expression.Call(parameter, typeof(T).GetMethod(methodName));
|
||||
var lambda = Expression.Lambda<Action<T>>(methodCall, parameter);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态调用无参有返回值方法
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="methodName"></param>
|
||||
/// <returns></returns>
|
||||
public static Func<T, TResult> MethodCallerHaveResul<T, TResult>(string methodName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{methodName}.MethodCaller";
|
||||
return (Func<T, TResult>)Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateHaveResult<T, TResult>(methodName));
|
||||
}
|
||||
|
||||
private static Func<T, TResult> CreateMethodCallerDelegateHaveResult<T, TResult>(string methodName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var methodCall = Expression.Call(parameter, typeof(T).GetMethod(methodName));
|
||||
var lambda = Expression.Lambda<Func<T, TResult>>(methodCall, parameter);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 动态调用单参数无返回值的方法
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TParam"></typeparam>
|
||||
/// <param name="methodName"></param>
|
||||
/// <returns></returns>
|
||||
public static Action<T, TParam> MethodCaller<T, TParam>(string methodName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{methodName}.MethodCallerWithParam";
|
||||
return (Action<T, TParam>)Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate<T, TParam>(methodName));
|
||||
}
|
||||
|
||||
private static Action<T, TParam> CreateMethodCallerDelegate<T, TParam>(string methodName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var argument = Expression.Parameter(typeof(TParam), "argument");
|
||||
var methodCall = Expression.Call(parameter, typeof(T).GetMethod(methodName), argument);
|
||||
var lambda = Expression.Lambda<Action<T, TParam>>(methodCall, parameter, argument);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态调用单参数有返回值的方法
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TParam"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="methodName"></param>
|
||||
/// <returns></returns>
|
||||
public static Func<T, TParam, TResult> MethodCallerWithResult<T, TParam, TResult>(string methodName)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{methodName}.MethodCallerWithResult";
|
||||
return (Func<T, TParam, TResult>)Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate<T, TParam, TResult>(methodName));
|
||||
}
|
||||
|
||||
private static Func<T, TParam, TResult> CreateMethodCallerDelegate<T, TParam, TResult>(string methodName)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var argument = Expression.Parameter(typeof(TParam), "argument");
|
||||
var methodCall = Expression.Call(parameter, typeof(T).GetMethod(methodName), argument);
|
||||
var lambda = Expression.Lambda<Func<T, TParam, TResult>>(methodCall, parameter, argument);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 动态调用多参无返回值的方法
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="methodName"></param>
|
||||
/// <param name="parameterTypes"></param>
|
||||
/// <returns></returns>
|
||||
public static Action<T, object[]> MethodCaller<T>(string methodName, params Type[] parameterTypes)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{methodName}.MethodCaller";
|
||||
return (Action<T, object[]>)Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate<T>(methodName, parameterTypes));
|
||||
}
|
||||
|
||||
private static Action<T, object[]> CreateMethodCallerDelegate<T>(string methodName, Type[] parameterTypes)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(T), "instance");
|
||||
var arguments = parameterTypes.Select((type, index) =>
|
||||
Expression.Parameter(typeof(object), $"arg{index}")
|
||||
).ToList();
|
||||
|
||||
var convertedArguments = arguments.Select((arg, index) =>
|
||||
Expression.Convert(arg, parameterTypes[index])
|
||||
).ToList();
|
||||
|
||||
var methodInfo = typeof(T).GetMethod(methodName, parameterTypes);
|
||||
|
||||
if (methodInfo == null)
|
||||
{
|
||||
throw new ArgumentException($"Method '{methodName}' not found in type '{typeof(T).FullName}' with given parameter types.");
|
||||
}
|
||||
|
||||
var methodCall = Expression.Call(parameter, methodInfo, convertedArguments);
|
||||
var lambda = Expression.Lambda<Action<T, object[]>>(methodCall, new[] { parameter }.Concat(arguments));
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 动态调用多参有返回值的方法
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="methodName"></param>
|
||||
/// <param name="parameterTypes"></param>
|
||||
/// <returns></returns>
|
||||
public static Func<T, object[], TResult> MethodCallerHaveResult<T, TResult>(string methodName, Type[] parameterTypes)
|
||||
{
|
||||
string cacheKey = $"{typeof(T).FullName}.{methodName}.MethodCallerHaveResult";
|
||||
return (Func<T, object[], TResult>)Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate<T, TResult>(methodName, parameterTypes));
|
||||
}
|
||||
|
||||
private static Func<T, object[], TResult> CreateMethodCallerDelegate<T, TResult>(string methodName, Type[] parameterTypes)
|
||||
{
|
||||
var instanceParam = Expression.Parameter(typeof(T), "instance");
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
|
||||
var convertedArgs = new Expression[parameterTypes.Length];
|
||||
for (int i = 0; i < parameterTypes.Length; i++)
|
||||
{
|
||||
var index = Expression.Constant(i);
|
||||
var argType = parameterTypes[i];
|
||||
var arrayIndex = Expression.ArrayIndex(argsParam, index);
|
||||
var convertedArg = Expression.Convert(arrayIndex, argType);
|
||||
convertedArgs[i] = convertedArg;
|
||||
}
|
||||
|
||||
var methodInfo = typeof(T).GetMethod(methodName, parameterTypes);
|
||||
|
||||
if (methodInfo == null)
|
||||
{
|
||||
throw new ArgumentException($"Method '{methodName}' not found in type '{typeof(T).FullName}' with given parameter types.");
|
||||
}
|
||||
|
||||
var methodCall = Expression.Call(instanceParam, methodInfo, convertedArgs);
|
||||
var lambda = Expression.Lambda<Func<T, object[], TResult>>(methodCall, instanceParam, argsParam);
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
*/
|
||||
|
||||
#endregion
|
||||
#region 暂时不删(已注释)
|
||||
/* /// <summary>
|
||||
/// 表达式树构建多个参数,有返回值的方法
|
||||
/// </summary>
|
||||
public static Delegate MethodCallerHaveResult(Type type, string methodName, Type[] parameterTypes)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodName}.MethodCallerHaveResult";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateHaveResult(type, methodName, parameterTypes));
|
||||
}
|
||||
|
||||
private static Delegate CreateMethodCallerDelegateHaveResult(Type type, string methodName, Type[] parameterTypes)
|
||||
{
|
||||
var instanceParam = Expression.Parameter(typeof(object), "instance");
|
||||
var argsParam = Expression.Parameter(typeof(object[]), "args");
|
||||
var convertedArgs = parameterTypes.Select((paramType, index) =>
|
||||
Expression.Convert(Expression.ArrayIndex(argsParam, Expression.Constant(index)), paramType)
|
||||
).ToArray();
|
||||
var methodCall = Expression.Call(Expression.Convert(instanceParam, type), type.GetMethod(methodName, parameterTypes), convertedArgs);
|
||||
var lambda = Expression.Lambda(Expression.Convert(methodCall, typeof(object)), instanceParam, argsParam);
|
||||
return lambda.Compile();
|
||||
}*/
|
||||
|
||||
|
||||
|
||||
/*/// <summary>
|
||||
/// 表达式反射 构建 无返回值、无参数 的委托
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="methodName"></param>
|
||||
/// <param name="parameterTypes"></param>
|
||||
/// <returns></returns>
|
||||
public static Delegate MethodCaller(Type type, string methodName, Type[] parameterTypes)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodName}.{string.Join(",", parameterTypes.Select(t => t.FullName))}.MethodCaller";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegate(type, methodName, parameterTypes));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 表达式反射 构建 无返回值、无参数 的委托
|
||||
/// </summary>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="methodName"></param>
|
||||
/// <param name="parameterTypes"></param>
|
||||
/// <returns></returns>
|
||||
private static Delegate CreateMethodCallerDelegate(Type type, string methodName, Type[] parameterTypes)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var arguments = parameterTypes.Select((paramType, index) => Expression.Parameter(paramType, $"param{index}")).ToArray();
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type), type.GetMethod(methodName, parameterTypes), arguments);
|
||||
|
||||
var delegateType = Expression.GetActionType(new[] { typeof(object) }.Concat(parameterTypes).ToArray());
|
||||
var lambda = Expression.Lambda(delegateType, methodCall, new[] { parameter }.Concat(arguments).ToArray());
|
||||
return lambda.Compile();
|
||||
}
|
||||
*/
|
||||
/*public static Delegate MethodCallerHaveResult(Type type, string methodName, Type returnType, Type[] parameterTypes)
|
||||
{
|
||||
string cacheKey = $"{type.FullName}.{methodName}.{string.Join(",", parameterTypes.Select(t => t.FullName))}.MethodCallerHaveResult";
|
||||
return Cache.GetOrAdd(cacheKey, _ => CreateMethodCallerDelegateHaveResult(type, methodName, returnType, parameterTypes));
|
||||
}
|
||||
|
||||
private static Delegate CreateMethodCallerDelegateHaveResult(Type type, string methodName, Type returnType, Type[] parameterTypes)
|
||||
{
|
||||
var parameter = Expression.Parameter(typeof(object), "instance");
|
||||
var arguments = parameterTypes.Select((paramType, index) => Expression.Parameter(paramType, $"param{index}")).ToArray();
|
||||
var methodCall = Expression.Call(Expression.Convert(parameter, type), type.GetMethod(methodName, parameterTypes), arguments);
|
||||
|
||||
var delegateType = Expression.GetFuncType(new[] { typeof(object) }.Concat(parameterTypes).Concat(new[] { typeof(object) }).ToArray());
|
||||
var lambda = Expression.Lambda(delegateType, Expression.Convert(methodCall, typeof(object)), new[] { parameter }.Concat(arguments).ToArray());
|
||||
return lambda.Compile();
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
94
Library/DynamicFlow/Tool/TcsSignal.cs
Normal file
94
Library/DynamicFlow/Tool/TcsSignal.cs
Normal file
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Serein.DynamicFlow.Tool
|
||||
{
|
||||
public class TcsSignalException : Exception
|
||||
{
|
||||
public FfState FfState { get; set; }
|
||||
public TcsSignalException(string? message) : base(message)
|
||||
{
|
||||
FfState = FfState.Cancel;
|
||||
}
|
||||
}
|
||||
|
||||
public class TcsSignal<TSignal> where TSignal : struct, Enum
|
||||
{
|
||||
|
||||
public ConcurrentDictionary<TSignal, Stack<TaskCompletionSource<object>>> TcsEvent { get; } = new();
|
||||
|
||||
// public object tcsObj = new object();
|
||||
|
||||
public bool TriggerSignal<T>(TSignal signal, T state)
|
||||
{
|
||||
if (TcsEvent.TryRemove(signal, out var waitTcss))
|
||||
{
|
||||
while (waitTcss.Count > 0)
|
||||
{
|
||||
waitTcss.Pop().SetResult(state);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
lock (TcsEvent)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public TaskCompletionSource<object> CreateTcs(TSignal signal)
|
||||
{
|
||||
|
||||
var tcs = new TaskCompletionSource<object>();
|
||||
TcsEvent.GetOrAdd(signal, _ => new Stack<TaskCompletionSource<object>>()).Push(tcs);
|
||||
return tcs;
|
||||
lock (TcsEvent)
|
||||
{
|
||||
/*if(TcsEvent.TryRemove(signal, out var tcss))
|
||||
{
|
||||
//tcs.TrySetException(new TcsSignalException("试图获取已存在的任务"));
|
||||
throw new TcsSignalException("试图获取已存在的任务");
|
||||
}*/
|
||||
|
||||
|
||||
/*TcsEvent.TryAdd(signal, tcs);
|
||||
return tcs;*/
|
||||
}
|
||||
}
|
||||
//public TaskCompletionSource<object> GetOrCreateTcs(TSignal signal)
|
||||
//{
|
||||
// lock (tcsObj)
|
||||
// {
|
||||
// var tcs = TcsEvent.GetOrAdd(signal, _ => new TaskCompletionSource<object>());
|
||||
// if (tcs.Task.IsCompleted)
|
||||
// {
|
||||
// TcsEvent.TryRemove(signal, out _);
|
||||
// tcs = new TaskCompletionSource<object>();
|
||||
// TcsEvent[signal] = tcs;
|
||||
// }
|
||||
// return tcs;
|
||||
// }
|
||||
//}
|
||||
|
||||
public void CancelTask()
|
||||
{
|
||||
lock(TcsEvent)
|
||||
{
|
||||
|
||||
foreach (var tcss in TcsEvent.Values)
|
||||
{
|
||||
while (tcss.Count > 0)
|
||||
{
|
||||
tcss.Pop().SetException(new TcsSignalException("Task Cancel"));
|
||||
}
|
||||
}
|
||||
TcsEvent.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
43
Library/DynamicFlow/Tool/TypeDefinition.cs
Normal file
43
Library/DynamicFlow/Tool/TypeDefinition.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using Serein.DynamicFlow;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Reflection.Metadata.Ecma335;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Serein.DynamicFlow.Tool
|
||||
{
|
||||
|
||||
|
||||
/* /// <summary>
|
||||
/// 标记一个方法是什么类型,加载dll后用来拖拽到画布中
|
||||
/// </summary>
|
||||
[AttributeUsage( AttributeTargets.Parameter)]
|
||||
public class ObjDetailAttribute : Attribute
|
||||
{
|
||||
public bool Scan { get; set; }
|
||||
public object @object { get; }
|
||||
public DynamicNodeType MethodDynamicType { get; }
|
||||
|
||||
public ObjDetailAttribute(DynamicNodeType methodDynamicType, object tmpObject = null, bool scan = true)
|
||||
{
|
||||
@object = tmpObject;
|
||||
MethodDynamicType = methodDynamicType;
|
||||
Scan = scan;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/* /// <summary>
|
||||
/// 状态接口
|
||||
/// </summary>
|
||||
public interface IState: IDynamic
|
||||
{
|
||||
/// <summary>
|
||||
/// 返回状态
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
string GetState(DynamicContext context);
|
||||
}*/
|
||||
}
|
||||
Reference in New Issue
Block a user