diff --git a/Test/TestWeb/Components/Pages/Home.razor b/Test/TestWeb/Components/Pages/Home.razor
index 9ec490f..dae7f54 100644
--- a/Test/TestWeb/Components/Pages/Home.razor
+++ b/Test/TestWeb/Components/Pages/Home.razor
@@ -2,12 +2,15 @@
@using System.Diagnostics.CodeAnalysis
@using LoggerProviderExtensions.HubLogger
@using System.Text
+@using MT.Toolkit
@implements IAsyncDisposable
Home
@logContent.ToString()
+
+
Welcome to your new app.
@code {
[Inject, NotNull] ILogger? Logger { get; set; }
@@ -18,33 +21,42 @@ Welcome to your new app.
base.OnInitialized();
// _ = StartFetchLog();
Channel.OnLog += HandleLog;
+ debounce = Debounce.Create(Log2, 1000);
+ throttle = Throttle.Create(Log2, 1000);
}
private void HandleLog(LoggerProviderExtensions.StructuredLogEntry entry)
{
logContent.AppendLine($"{entry.Category}: {entry.MessageTemplate}");
- Console.WriteLine($"{entry.Category}: {entry.MessageTemplate}");
InvokeAsync(StateHasChanged);
}
- // private async Task StartFetchLog()
- // {
- // await foreach (var item in Channel.LogEntries)
- // {
- // logContent.AppendLine($"{item.Category}: {item.MessageTemplate}");
- // Console.WriteLine($"{item.Category}: {item.MessageTemplate}");
- // StateHasChanged();
- // }
- // }
-
private void Log()
{
Logger.LogInformation("This is a log message at {Time}", DateTime.Now);
}
+ private void Log2(string type)
+ {
+ Logger.LogInformation("{type} log at {Time}", type, DateTime.Now);
+ }
+
+ private Debounce? debounce;
+ private Throttle? throttle;
+
+ private async Task DebounceTest()
+ {
+ _ = debounce!.InvokeAsync("DebounceTest");
+ }
+ private async Task ThrottleTest()
+ {
+ _ = throttle!.InvokeAsync("ThrottleTest");
+ }
public ValueTask DisposeAsync()
{
Channel.OnLog -= HandleLog;
+ debounce!.Dispose();
+ throttle!.Dispose();
return ValueTask.CompletedTask;
}
}
\ No newline at end of file
diff --git "a/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md" "b/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md"
index bc21d44..a755658 100644
--- "a/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md"
+++ "b/doc/\346\233\264\346\226\260\346\227\245\345\277\227.md"
@@ -1,5 +1,8 @@
## 版本功能更新日志
+### v2026.06.02.1
+- ⚡️支持AOT编译
+
### v2.1.9.0
- ⚡️移除Mapper相关代码 -> 使用`AutoGenMapperGenerator`代替
diff --git a/src/SoapRequestHelper/SoapRequestHelper.csproj b/src/SoapRequestHelper/SoapRequestHelper.csproj
index 749f285..96a8bf0 100644
--- a/src/SoapRequestHelper/SoapRequestHelper.csproj
+++ b/src/SoapRequestHelper/SoapRequestHelper.csproj
@@ -12,6 +12,7 @@
True
True
nuget.md
+ true
diff --git a/src/SoapRequestHelper/SoapResponse.cs b/src/SoapRequestHelper/SoapResponse.cs
index 67d5467..c533cef 100644
--- a/src/SoapRequestHelper/SoapResponse.cs
+++ b/src/SoapRequestHelper/SoapResponse.cs
@@ -232,6 +232,9 @@ private static DataTable CreateDataTable(IEnumerable schema, IEnumerab
return dt;
}
+#if NET8_0_OR_GREATER
+ [return: System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembers(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields)]
+#endif
private static Type ConvertElementType(string type)
{
return type switch
@@ -245,10 +248,10 @@ private static Type ConvertElementType(string type)
_ => typeof(string),
};
}
- static readonly ConcurrentDictionary tryParseCache = [];
+
private static object? Parse(string? input, Type type)
{
- if ( string.IsNullOrEmpty(input))
+ if (string.IsNullOrEmpty(input))
{
return default;
}
@@ -257,20 +260,54 @@ private static Type ConvertElementType(string type)
return input.Trim();
}
type = Nullable.GetUnderlyingType(type) ?? type;
- var method = tryParseCache.GetOrAdd(type, t =>
- {
- return t.GetMethod("TryParse", [typeof(string), t.MakeByRefType()]);
- });
- if (method == null)
+
+ if (TryParse(input, type, out var value))
{
- return default;
+ return value;
}
- object?[] parameters = [input, default];
- var r = method.Invoke(null, parameters);
- if (r is bool b && b == true)
+
+ return default;
+
+ static bool TryParse(string text, Type type, out object? value)
{
- return parameters[1];
+ if (type == typeof(DateTime))
+ {
+ _ = DateTime.TryParse(text, out var v);
+ value = v;
+ return true;
+ }
+ else if (type == typeof(bool))
+ {
+ _ = bool.TryParse(text, out var v);
+ value = v;
+ return true;
+ }
+ else if (type == typeof(int))
+ {
+ _ = int.TryParse(text, out var v);
+ value = v;
+ return true;
+ }
+ else if (type == typeof(decimal))
+ {
+ _ = decimal.TryParse(text, out var v);
+ value = v;
+ return true;
+ }
+ else if (type == typeof(long))
+ {
+ _ = long.TryParse(text, out var v);
+ value = v;
+ return true;
+ }
+ else if (type == typeof(short))
+ {
+ _ = short.TryParse(text, out var v);
+ value = v;
+ return true;
+ }
+ value = default;
+ return false;
}
- return default;
}
}
\ No newline at end of file
diff --git a/src/Toolkit/DataTableExtension/DataTableBuilder.cs b/src/Toolkit/DataTableExtension/DataTableBuilder.cs
index eab2ecb..fda40cb 100644
--- a/src/Toolkit/DataTableExtension/DataTableBuilder.cs
+++ b/src/Toolkit/DataTableExtension/DataTableBuilder.cs
@@ -1,76 +1,81 @@
using System;
using System.Collections.Generic;
using System.Data;
+using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
-namespace MT.Toolkit.DataTableExtension
+namespace MT.Toolkit.DataTableExtension;
+
+internal static class DataTableBuilder<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+T>
{
- public static class DataTableBuilder
- {
- private static Func? func;
+ private static Func? func;
- public static Func Build(DataColumnCollection dataColumn, bool mapAll)
- {
- if (func != null) return func;
- func = CreateFunc(typeof(T), dataColumn, mapAll);
- return func;
- }
+ public static Func Build(DataColumnCollection dataColumn, bool mapAll)
+ {
+ if (func != null) return func;
+ func = CreateFunc(dataColumn, mapAll);
+ return func;
+ }
- static Func CreateFunc(Type tarType, DataColumnCollection cols, bool mapAll)
- {
- // Datarow row;
- ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row");
- List bindings = new List();
- // fields
- var fields = tarType.GetFields(BindingFlags.Public | BindingFlags.Instance);
- foreach (FieldInfo field in fields)
- {
- void work()
- {
- if (cols.Contains(field.Name))
- {
- DataColumn col = cols[field.Name]!;
- var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, field.FieldType);
- MemberAssignment memberAssignment = Expression.Bind(field, valueExp);
- bindings.Add(memberAssignment);
- return;
- }
- if (mapAll)
- {
- throw new ArgumentException($"Property {field.Name} is not matched by any column in datatable");
- }
- }
- work();
- }
+ static Func CreateFunc(DataColumnCollection cols, bool mapAll)
+ {
+ Type tarType = typeof(T);
+ // Datarow row;
+ ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row");
+ List bindings = [];
+ // fields
+ var fields = tarType.GetFields(BindingFlags.Public | BindingFlags.Instance);
+ foreach (FieldInfo field in fields)
+ {
+ void work()
+ {
+ if (cols.Contains(field.Name))
+ {
+ DataColumn col = cols[field.Name]!;
+ var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, field.FieldType);
+ MemberAssignment memberAssignment = Expression.Bind(field, valueExp);
+ bindings.Add(memberAssignment);
+ return;
+ }
+ if (mapAll)
+ {
+ throw new ArgumentException($"Property {field.Name} is not matched by any column in datatable");
+ }
+ }
+ work();
+ }
- // properties
- var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
- foreach (PropertyInfo prop in props)
- {
- void work()
- {
- if (cols.Contains(prop.Name))
- {
- if (!prop.CanWrite) return;
- DataColumn col = cols[prop.Name]!;
- var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType);
- MemberAssignment memberAssignment = Expression.Bind(prop, valueExp);
- bindings.Add(memberAssignment);
- return;
- }
- if (mapAll)
- {
- throw new ArgumentException($"Property {prop.Name} is not matched by any column in datatable");
- }
+ // properties
+ var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
+ foreach (PropertyInfo prop in props)
+ {
+ void work()
+ {
+ if (cols.Contains(prop.Name))
+ {
+ if (!prop.CanWrite) return;
+ DataColumn col = cols[prop.Name]!;
+ var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType);
+ MemberAssignment memberAssignment = Expression.Bind(prop, valueExp);
+ bindings.Add(memberAssignment);
+ return;
+ }
+ if (mapAll)
+ {
+ throw new ArgumentException($"Property {prop.Name} is not matched by any column in datatable");
+ }
- }
- work();
- }
- MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(tarType), bindings);
- var lambda = Expression.Lambda>(memberInitExpression, rowExp);
- return lambda.Compile();
- }
+ }
+ work();
+ }
+ MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(tarType), bindings);
+ var lambda = Expression.Lambda>(memberInitExpression, rowExp);
+ return lambda.Compile();
+ }
- }
}
diff --git a/src/Toolkit/DataTableExtension/DataTableHelper.cs b/src/Toolkit/DataTableExtension/DataTableHelper.cs
index 7c70f2c..5f29489 100644
--- a/src/Toolkit/DataTableExtension/DataTableHelper.cs
+++ b/src/Toolkit/DataTableExtension/DataTableHelper.cs
@@ -1,113 +1,214 @@
using System;
using System.Collections.Generic;
-using System.Text;
using System.Data;
+using System.Diagnostics.CodeAnalysis;
+using System.Text;
+
+namespace MT.Toolkit.DataTableExtension;
-namespace MT.Toolkit.DataTableExtension
+///
+/// DataTable帮助类
+///
+public static class DataTableHelper
{
- public static class DataTableHelper
+ ///
+ /// 是否有至少一行数据
+ ///
+ ///
+ ///
+ public static bool HasRows(this DataTable? dt)
+ {
+ return dt is not null && dt.Rows.Count > 0;
+ }
+
+ ///
+ /// 将DataTable转换为可枚举的对象集合
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable ToEnumerable<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+ T>(this DataTable? self, bool mapAllFields = false)
{
- public static bool HasRows(this DataTable dt)
+ if (self is null)
{
- return dt != null && dt.Rows.Count > 0;
+ yield break;
}
- public static IEnumerable ToEnumerable(this DataTable self, bool mapAllFields = false)
+ foreach (DataRow row in self.Rows)
{
- foreach (DataRow row in self.Rows)
- {
- yield return row.Parse(mapAllFields);
- }
+ yield return row.Parse(mapAllFields);
}
+ }
- public static IEnumerable Select(this DataTable self, Func filter, bool mapAllFields = false)
+ ///
+ /// 将DataTable转换为可枚举的对象集合,并根据指定的过滤条件进行筛选
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable Select<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+ T>(this DataTable self, Func filter, bool mapAllFields = false)
+ {
+ foreach (DataRow row in self.Rows)
{
- foreach (DataRow row in self.Rows)
+ if (filter.Invoke(row))
{
- if (filter.Invoke(row))
- {
- yield return row.Parse(mapAllFields);
- }
+ yield return row.Parse(mapAllFields);
}
}
+ }
- public static IEnumerable Select(this DataTable self, Func filter, bool mapAllFields = false)
+ ///
+ /// 将DataTable转换为可枚举的对象集合,并根据指定的过滤条件进行筛选
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static IEnumerable Select<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+ T>(this DataTable self, Func filter, bool mapAllFields = false)
+ {
+ foreach (DataRow row in self.Rows)
{
- foreach (DataRow row in self.Rows)
+ var t = row.Parse(mapAllFields);
+ if (filter.Invoke(t))
{
- var t = row.Parse(mapAllFields);
- if (filter.Invoke(t))
- {
- yield return t;
- }
+ yield return t;
}
}
+ }
- public static T Parse(this DataRow row, bool mapAllFields)
+ ///
+ /// 转换DataRow为对象
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static T Parse<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+ T>(this DataRow row, bool mapAllFields)
+ {
+ var columns = row.Table.Columns;
+ var func = DataTableBuilder.Build(columns, mapAllFields);
+ return (T)func.Invoke(row);
+ }
+
+ ///
+ /// 获取DataRow中指定列的值,并将其转换为指定类型
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static T GetValue(this DataRow self, string key)
+ {
+ if (!self.Table.Columns.Contains(key))
{
- var columns = row.Table.Columns;
- var func = DataTableBuilder.Build(columns, mapAllFields);
- return (T)func.Invoke(row);
+ throw new ArgumentException($"column {key} is not contains in datatable");
}
- public static T GetValue(this DataRow self, string key)
+ if (self.IsNull(key))
{
- if (!self.Table.Columns.Contains(key))
- {
- throw new ArgumentException($"column {key} is not contains in datatable");
- }
-
- if (self.IsNull(key))
- {
- return default!;
- }
- var val = self[key];
-
- var undeylying = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
- return (T)Convert.ChangeType(val, undeylying);
+ return default!;
}
+ var val = self[key];
- public static string? GetValue(this DataRow self, string key)
- {
- if (!self.Table.Columns.Contains(key))
- {
- throw new ArgumentException($"column {key} is not contains in datatable");
- }
+ var undeylying = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
+ return (T)Convert.ChangeType(val, undeylying);
+ }
- if (self.IsNull(key))
- {
- return default;
- }
- var val = self[key];
- return val?.ToString();
+ ///
+ /// 获取DataRow中指定列的值, 并将其转换为字符串
+ ///
+ ///
+ ///
+ ///
+ ///
+ public static string? GetValue(this DataRow self, string key)
+ {
+ if (!self.Table.Columns.Contains(key))
+ {
+ throw new ArgumentException($"column {key} is not contains in datatable");
}
- public static void MapFromTable(this T self, DataTable source)
+ if (self.IsNull(key))
{
- var action = MapFromExpression.Build(source.Columns);
- action?.Invoke(self, source.Rows[0]);
+ return default;
}
+ var val = self[key];
+ return val?.ToString();
+ }
+
+ ///
+ /// 从DataTable的第一行数据映射到对象实例中
+ ///
+ ///
+ ///
+ ///
+ public static void MapFromTable<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+ T>(this T self, DataTable? source)
+ {
+ if (source is null)
+ return;
+ var action = MapFromExpression.Build(source.Columns);
+ action?.Invoke(self, source.Rows[0]);
+ }
- public static DataRow? FirstRow(this DataTable dt)
+ ///
+ /// 获取DataTable的第一行数据
+ ///
+ ///
+ ///
+ public static DataRow? FirstRow(this DataTable? dt)
+ {
+ if (dt?.Rows.Count == 0)
{
- if (dt?.Rows.Count == 0)
- {
- return null;
- }
- return dt?.Rows[0];
+ return null;
}
+ return dt?.Rows[0];
+ }
- public static DataTable ToDataTable(this IEnumerable datas)
+ ///
+ /// 实体集合转换为DataTable
+ ///
+ ///
+ ///
+ ///
+ public static DataTable ToDataTable<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+ T>(this IEnumerable datas)
+ {
+ var dt = MapToDataTableExtension.GetDataTable();
+ foreach (var item in datas)
{
- var dt = MapToDataTableExtension.GetDataTable();
- foreach (var item in datas)
- {
- var row = dt.NewRow();
- MapToDataTableExtension.FillDataRow(item, row);
- dt.Rows.Add(row);
- }
- //dt.Columns.Add()
- return dt;
+ var row = dt.NewRow();
+ MapToDataTableExtension.FillDataRow(item, row);
+ dt.Rows.Add(row);
}
+ //dt.Columns.Add()
+ return dt;
}
}
diff --git a/src/Toolkit/DataTableExtension/MapFromExpression.cs b/src/Toolkit/DataTableExtension/MapFromExpression.cs
index d0fbe7b..6afda4f 100644
--- a/src/Toolkit/DataTableExtension/MapFromExpression.cs
+++ b/src/Toolkit/DataTableExtension/MapFromExpression.cs
@@ -2,110 +2,136 @@
using System;
using System.Collections.Generic;
using System.Data;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
-namespace MT.Toolkit.DataTableExtension
+namespace MT.Toolkit.DataTableExtension;
+
+internal static class MapFromExpression<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+T>
{
- public static class MapFromExpression
+ static Dictionary> actions = new Dictionary>();
+ public static Action Build(DataColumnCollection cols)
{
- static Dictionary> actions = new Dictionary>();
- public static Action Build(DataColumnCollection cols)
+ var columnNames = from col in cols.Cast()
+ select col.ColumnName;
+ var key = string.Join("_", columnNames);
+ if (actions.TryGetValue(key, out var action))
{
- var columnNames = from col in cols.Cast()
- select col.ColumnName;
- var key = string.Join("_", columnNames);
- if (actions.TryGetValue(key, out var action))
- {
- return action;
- }
- action = CreateAction(cols);
- actions.Add(key, action);
return action;
}
+ action = CreateAction(cols);
+ actions.Add(key, action);
+ return action;
+ }
- private static Action CreateAction(DataColumnCollection cols)
+ private static Action CreateAction(DataColumnCollection cols)
+ {
+ ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row");
+ ParameterExpression tarExp = Expression.Parameter(typeof(T), "tar");
+ var tarType = typeof(T);
+ List body = new List();
+ // properties
+ var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
+ foreach (DataColumn col in cols)
{
- ParameterExpression rowExp = Expression.Parameter(typeof(DataRow), "row");
- ParameterExpression tarExp = Expression.Parameter(typeof(T), "tar");
- var tarType = typeof(T);
- List body = new List();
- // properties
- var props = tarType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
- foreach (DataColumn col in cols)
+ var prop = props.FirstOrDefault(p => p.Name.Equals(col.ColumnName, StringComparison.CurrentCultureIgnoreCase));
+ if (prop != null && prop.CanWrite && prop.SetMethod is not null)
{
- var prop = props.FirstOrDefault(p => p.Name.ToLower() == col.ColumnName.ToLower());
- if (prop != null && prop.CanWrite)
- {
- var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType);
- MethodCallExpression propAssign = Expression.Call(tarExp, prop.SetMethod, valueExp);
- body.Add(propAssign);
- }
+ var valueExp = TableExpressionBase.GetTargetValueExpression(col, rowExp, prop.PropertyType);
+ MethodCallExpression propAssign = Expression.Call(tarExp, prop.SetMethod, valueExp);
+ body.Add(propAssign);
}
- var block = Expression.Block(body);
- var lambda = Expression.Lambda>(block, tarExp, rowExp);
- return lambda.Compile();
}
+ var block = Expression.Block(body);
+ var lambda = Expression.Lambda>(block, tarExp, rowExp);
+ return lambda.Compile();
+ }
+}
+
+internal static class ExpressionUsedMethods
+{
+ //public static MethodInfo DataColumnAdd = typeof(DataColumnCollection).GetMethod(nameof(DataColumnCollection.Add), [typeof(string), typeof(Type)])!;
+ //public static MethodInfo DataRowSet = typeof(DataRow).GetMethod("set_Item", [typeof(string), typeof(object)])!;
+#if NET8_0_OR_GREATER
+ [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2111",
+ Justification = "通过 AddColumn 的 columnType 参数上的 DynamicallyAccessedMembers 保证安全,且实际调用时传入的类型已满足保留要求")]
+#endif
+ public static MethodInfo DataColumnAdd = typeof(ExpressionUsedMethods).GetMethod(nameof(AddColumn), [typeof(DataTable), typeof(string), typeof(Type)])!;
+ public static MethodInfo DataRowSet = typeof(ExpressionUsedMethods).GetMethod(nameof(SetRowValue), [typeof(DataRow), typeof(string), typeof(object)])!;
+ public static void AddColumn(DataTable dataTable, string columnName,
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields|DynamicallyAccessedMemberTypes.PublicProperties)]
+#endif
+ Type columnType)
+ {
+ dataTable.Columns.Add(columnName, columnType);
}
- internal static class ExpressionUsedMethods
+ public static void SetRowValue(DataRow row, string columnName, object value)
{
- public static MethodInfo DataColumnAdd = typeof(DataColumnCollection).GetMethod(nameof(DataColumnCollection.Add), [typeof(string), typeof(Type)])!;
- public static MethodInfo DataRowSet = typeof(DataRow).GetMethod("set_Item", [typeof(string), typeof(object)])!;
+ row[columnName] = value;
}
+}
+
+internal static class MapToDataTableExtension<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+T>
+{
+ private static readonly Func createTable;
+ private static readonly Action fillRow;
- internal static class MapToDataTableExtension
+ static MapToDataTableExtension()
{
- private static Func createTable;
- private static Action fillRow;
+ createTable = BuildCreateTableFunc();
+ fillRow = BuildCreateRowFunc();
+ }
- static MapToDataTableExtension()
- {
- createTable = BuildCreateTableFunc();
- fillRow = BuildCreateRowFunc();
- }
+ internal static DataTable GetDataTable() => createTable.Invoke();
+ internal static void FillDataRow(T value, DataRow row) => fillRow.Invoke(value, row);
+ private static Func BuildCreateTableFunc()
+ {
+ var dtExp = Expression.Variable(typeof(DataTable));
+ var ctorMethod = typeof(DataTable).GetConstructor([typeof(string)])!;
+ var newDt = Expression.New(ctorMethod, [Expression.Constant(typeof(T).Name, typeof(string))]);
+ var assign = Expression.Assign(dtExp, newDt);
- internal static DataTable GetDataTable() => createTable.Invoke();
- internal static void FillDataRow(T value, DataRow row) => fillRow.Invoke(value, row);
- private static Func BuildCreateTableFunc()
+ List body = [
+ dtExp,assign
+ ];
+ var props = typeof(T).GetProperties();
+ foreach (var item in props)
{
- var dtExp = Expression.Variable(typeof(DataTable));
- var ctorMethod = typeof(DataTable).GetConstructor([typeof(string)])!;
- var newDt = Expression.New(ctorMethod, [Expression.Constant(typeof(T).Name, typeof(string))]);
- var assign = Expression.Assign(dtExp, newDt);
-
- List body = [
- dtExp,assign
- ];
- var props = typeof(T).GetProperties();
- var columns = Expression.Property(dtExp, nameof(DataTable.Columns));
- foreach (var item in props)
- {
- if (!item.CanRead) continue;
- body.Add(Expression.Call(columns, ExpressionUsedMethods.DataColumnAdd, Expression.Constant(item.Name, typeof(string)), Expression.Constant(item.PropertyType, typeof(Type))));
- }
- body.Add(dtExp);
- var block = Expression.Block([dtExp], [.. body]);
- var lambda = Expression.Lambda>(block);
- return lambda.Compile();
+ if (!item.CanRead) continue;
+ body.Add(Expression.Call(dtExp, ExpressionUsedMethods.DataColumnAdd, Expression.Constant(item.Name, typeof(string)), Expression.Constant(item.PropertyType, typeof(Type))));
}
+ body.Add(dtExp);
+ var block = Expression.Block([dtExp], [.. body]);
+ var lambda = Expression.Lambda>(block);
+ return lambda.Compile();
+ }
- private static Action BuildCreateRowFunc()
+ private static Action BuildCreateRowFunc()
+ {
+ var val = Expression.Parameter(typeof(T), "p");
+ var row = Expression.Parameter(typeof(DataRow), "r");
+ var props = typeof(T).GetProperties();
+ List body = [];
+ foreach (var item in props)
{
- var val = Expression.Parameter(typeof(T), "p");
- var row = Expression.Parameter(typeof(DataRow), "r");
- var props = typeof(T).GetProperties();
- List body = [];
- foreach (var item in props)
- {
- if (!item.CanRead) continue;
- body.Add(Expression.Call(row, ExpressionUsedMethods.DataRowSet, Expression.Constant(item.Name, typeof(string)), Expression.Convert(Expression.Property(val, item), typeof(object))));
- }
- var block = Expression.Block( [.. body]);
- var lambda = Expression.Lambda>(block, val, row);
- return lambda.Compile();
+ if (!item.CanRead) continue;
+ body.Add(Expression.Call(row, ExpressionUsedMethods.DataRowSet, Expression.Constant(item.Name, typeof(string)), Expression.Convert(Expression.Property(val, item), typeof(object))));
}
+ var block = Expression.Block([.. body]);
+ var lambda = Expression.Lambda>(block, val, row);
+ return lambda.Compile();
}
}
diff --git a/src/Toolkit/DataTableExtension/TableExpressionBase.cs b/src/Toolkit/DataTableExtension/TableExpressionBase.cs
index edbd23f..31608d3 100644
--- a/src/Toolkit/DataTableExtension/TableExpressionBase.cs
+++ b/src/Toolkit/DataTableExtension/TableExpressionBase.cs
@@ -1,42 +1,43 @@
using MT.Toolkit.ExpressionHelper;
using System;
using System.Data;
+using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
namespace MT.Toolkit.DataTableExtension
{
- internal class TableExpressionBase
- {
- public static MethodInfo Datarow_getItem = typeof(DataRow).GetMethod("get_Item", new Type[] { typeof(string) });
- public static MethodInfo DataRow_IsNull = typeof(DataRow).GetMethod("IsNull", new Type[] { typeof(string) });
- public static Expression GetTargetValueExpression(DataColumn column, ParameterExpression parameterExpression, Type targetType)
- {
- MethodCallExpression rowObjExp = Expression.Call(parameterExpression, Datarow_getItem, Expression.Constant(column.ColumnName));
- MethodCallExpression checkNullExp = Expression.Call(parameterExpression, DataRow_IsNull, Expression.Constant(column.ColumnName));
- Expression e;
- Type t = column.DataType;
- if (targetType != typeof(byte[]))
- {
- e = Expression.Call(rowObjExp, typeof(object).GetMethod("ToString", Type.EmptyTypes));
- t = typeof(string);
- }
- else
- e = rowObjExp;
- Expression realValueExp = DataTypeConvert.GetConversionExpression(e, t, targetType);
- if (column.AllowDBNull)
- {
- return Expression.Condition(
- checkNullExp,
- Expression.Default(targetType),
- realValueExp,
- targetType
- );
- }
- else
- {
- return realValueExp;
- }
- }
- }
+ internal class TableExpressionBase
+ {
+ public static MethodInfo Datarow_getItem = typeof(DataRow).GetMethod("get_Item", [typeof(string)])!;
+ public static MethodInfo DataRow_IsNull = typeof(DataRow).GetMethod("IsNull", [typeof(string)])!;
+ public static Expression GetTargetValueExpression(DataColumn column, ParameterExpression parameterExpression, Type targetType)
+ {
+ MethodCallExpression rowObjExp = Expression.Call(parameterExpression, Datarow_getItem, Expression.Constant(column.ColumnName));
+ MethodCallExpression checkNullExp = Expression.Call(parameterExpression, DataRow_IsNull, Expression.Constant(column.ColumnName));
+ Expression e;
+ Type t = column.DataType;
+ if (targetType != typeof(byte[]))
+ {
+ e = Expression.Call(rowObjExp, typeof(object).GetMethod("ToString", Type.EmptyTypes)!);
+ t = typeof(string);
+ }
+ else
+ e = rowObjExp;
+ Expression realValueExp = DataTypeConvert.GetConversionExpression(e, t, targetType);
+ if (column.AllowDBNull)
+ {
+ return Expression.Condition(
+ checkNullExp,
+ Expression.Default(targetType),
+ realValueExp,
+ targetType
+ );
+ }
+ else
+ {
+ return realValueExp;
+ }
+ }
+ }
}
diff --git a/src/Toolkit/EnumExtensions/EnumHelper.cs b/src/Toolkit/EnumExtensions/EnumHelper.cs
index 2660132..dc22538 100644
--- a/src/Toolkit/EnumExtensions/EnumHelper.cs
+++ b/src/Toolkit/EnumExtensions/EnumHelper.cs
@@ -1,7 +1,9 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
@@ -16,28 +18,40 @@ namespace MT.Toolkit.EnumExtensions
///
public static class EnumHelper
{
- private static readonly ConcurrentDictionary<(Type, string), string> enumCache = [];
+ private static readonly ConcurrentDictionary> enumCache = [];
///
- ///
+ /// 获取枚举的显示名称
///
///
///
///
- public static string GetDisplayName(this T @enum) where T : Enum
+ public static string GetDisplayName<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
+#endif
+ T>(this T @enum) where T : Enum
{
- return enumCache.GetOrAdd((typeof(T), @enum.ToString()), key =>
+ var et = typeof(T);
+ var member = et.GetMember(@enum.ToString()).First();
+ if (!enumCache.TryGetValue(et, out var edic))
{
- var member = key.Item1.GetMember(key.Item2).FirstOrDefault();
- if (member != null)
+ edic = new();
+ enumCache.TryAdd(et, edic);
+ }
+ if (!edic.TryGetValue(member, out var des))
+ {
+ if (member.GetCustomAttribute() is { } displayAttr)
+ {
+ des = displayAttr.Name;
+ }
+ else if (member.GetCustomAttribute() is { } descriptionAttr)
{
- var displayAttr = member.GetCustomAttribute();
- if (displayAttr is not null)
- {
- return displayAttr.Name ?? key.Item2;
- }
+ des = descriptionAttr.Description;
}
- return key.Item2;
- });
+ des ??= @enum.ToString();
+ edic.TryAdd(member, des);
+ }
+ return des;
}
}
diff --git a/src/Toolkit/ExpressionHelper/DataTypeConvert.cs b/src/Toolkit/ExpressionHelper/DataTypeConvert.cs
index 27a9bfb..cce7d84 100644
--- a/src/Toolkit/ExpressionHelper/DataTypeConvert.cs
+++ b/src/Toolkit/ExpressionHelper/DataTypeConvert.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
@@ -8,151 +9,167 @@
using System.Text;
using System.Threading.Tasks;
-namespace MT.Toolkit.ExpressionHelper
+namespace MT.Toolkit.ExpressionHelper;
+
+internal class DataTypeConvert
{
- public class DataTypeConvert
+ public static Expression GetConversionExpression(Expression source,
+ Type sourceType,
+ Type targetType)
{
- public static Expression GetConversionExpression(Expression source, Type sourceType, Type targetType)
+ if (ReferenceEquals(sourceType, targetType))
{
- if (ReferenceEquals(sourceType, targetType))
- {
- return Expression.Convert(source, sourceType);
- }
- else if (ReferenceEquals(sourceType, typeof(string)))
- {
- // XXX.Parse()
- return GetParseExpression(source, targetType, CultureInfo.CurrentCulture);
- }
- else if (ReferenceEquals(targetType, typeof(string)))
- {
- // XXX.ToString()
- return Expression.Call(source, sourceType.GetMethod("ToString", Type.EmptyTypes)!);
- }
- else if (ReferenceEquals(targetType, typeof(bool)))
- {
- MethodInfo ToBooleanMethod = typeof(Convert).GetMethod("ToBoolean", new[] { sourceType });
- return Expression.Call(ToBooleanMethod, source);
- }
- else if (ReferenceEquals(sourceType, typeof(byte[])))
- {
- return GetArrayHandlerExpression(source, targetType);
- }
- else
- {
- return ConvertTypeExpression(source, sourceType, targetType);
- }
+ return Expression.Convert(source, sourceType);
}
- private static Expression GetArrayHandlerExpression(Expression sourceExpression, Type targetType)
+ else if (ReferenceEquals(sourceType, typeof(string)))
{
- Expression TargetExpression = default;
- if (ReferenceEquals(targetType, typeof(byte[])))
- {
- TargetExpression = sourceExpression;
- }
- else if (ReferenceEquals(targetType, typeof(MemoryStream)))
- {
- ConstructorInfo ConstructorInfo = targetType.GetConstructor(new[] { typeof(byte[]) });
- TargetExpression = Expression.New(ConstructorInfo, sourceExpression);
- }
- else
- {
- throw new ArgumentException("Cannot convert a byte array to " + targetType.Name);
- }
- return TargetExpression;
+ // XXX.Parse()
+ return GetParseExpression(source, targetType, CultureInfo.CurrentCulture);
+ }
+ else if (ReferenceEquals(targetType, typeof(string)))
+ {
+ // XXX.ToString()
+ return Expression.Call(source, typeof(Convert).GetMethod("ToString", [sourceType])!);
+ }
+ else if (ReferenceEquals(targetType, typeof(bool)))
+ {
+ MethodInfo ToBooleanMethod = typeof(Convert).GetMethod("ToBoolean", [sourceType])!;
+ return Expression.Call(ToBooleanMethod, source);
+ }
+ else if (ReferenceEquals(sourceType, typeof(byte[])))
+ {
+ return GetArrayHandlerExpression(source, targetType);
+ }
+ else
+ {
+ return ConvertTypeExpression(source, sourceType, targetType);
}
+ }
+ private static Expression GetArrayHandlerExpression(Expression sourceExpression, Type targetType)
+ {
+ Expression TargetExpression = default!;
+ if (ReferenceEquals(targetType, typeof(byte[])))
+ {
+ TargetExpression = sourceExpression;
+ }
+ else if (ReferenceEquals(targetType, typeof(MemoryStream)))
+ {
+ ConstructorInfo ConstructorInfo = typeof(MemoryStream).GetConstructor([typeof(byte[])])!;
+ TargetExpression = Expression.New(ConstructorInfo, sourceExpression);
+ }
+ else
+ {
+ throw new ArgumentException("Cannot convert a byte array to " + targetType.Name);
+ }
+ return TargetExpression;
+ }
- private static Expression GetParseExpression(Expression SourceExpression, Type TargetType, CultureInfo Culture)
+ private static Expression GetParseExpression(Expression SourceExpression, Type TargetType, CultureInfo Culture)
+ {
+ Type UnderlyingType = Nullable.GetUnderlyingType(TargetType) ?? TargetType;
+ if (UnderlyingType.IsEnum)
{
- Type UnderlyingType = Nullable.GetUnderlyingType(TargetType) ?? TargetType;
- if (UnderlyingType.IsEnum)
- {
- MethodCallExpression ParsedEnumExpression = GetEnumParseExpression(SourceExpression, UnderlyingType);
- //Enum.Parse returns an object that needs to be unboxed
- return Expression.Unbox(ParsedEnumExpression, TargetType);
- }
- else
+ MethodCallExpression ParsedEnumExpression = GetEnumParseExpression(SourceExpression, UnderlyingType);
+ //Enum.Parse returns an object that needs to be unboxed
+ return Expression.Unbox(ParsedEnumExpression, TargetType);
+ }
+ else
+ {
+ Expression valueExp = default!;
+ valueExp = UnderlyingType.FullName switch
{
- Expression ParseExpression = default;
- switch (UnderlyingType.FullName)
- {
- case "System.Byte":
- case "System.UInt16":
- case "System.UInt32":
- case "System.UInt64":
- case "System.SByte":
- case "System.Int16":
- case "System.Int32":
- case "System.Int64":
- case "System.Double":
- case "System.Decimal":
- ParseExpression = GetNumberParseExpression(SourceExpression, UnderlyingType, Culture);
- break;
- case "System.DateTime":
- ParseExpression = GetDateTimeParseExpression(SourceExpression, UnderlyingType, Culture);
- break;
- case "System.Boolean":
- case "System.Char":
- ParseExpression = GetGenericParseExpression(SourceExpression, UnderlyingType);
- break;
- default:
- throw new ArgumentException(string.Format("Conversion from {0} to {1} is not supported", "String", TargetType));
- }
- if (Nullable.GetUnderlyingType(TargetType) == null)
- {
- return ParseExpression;
- }
- else
- {
- //Convert to nullable if necessary
- return Expression.Convert(ParseExpression, TargetType);
- }
- }
- Expression GetGenericParseExpression(Expression sourceExpression, Type type)
+ "System.Byte" => NumberParseExpression(SourceExpression, Culture),
+ "System.UInt16" => NumberParseExpression(SourceExpression, Culture),
+ "System.UInt32" => NumberParseExpression(SourceExpression, Culture),
+ "System.UInt64" => NumberParseExpression(SourceExpression, Culture),
+ "System.SByte" => NumberParseExpression(SourceExpression, Culture),
+ "System.Int16" => NumberParseExpression(SourceExpression, Culture),
+ "System.Int32" => NumberParseExpression(SourceExpression, Culture),
+ "System.Int64" => NumberParseExpression(SourceExpression, Culture),
+ "System.Double" => NumberParseExpression(SourceExpression, Culture),
+ "System.Decimal" => NumberParseExpression(SourceExpression, Culture),
+ "System.DateTime" => GetDateTimeParseExpression(SourceExpression, Culture),
+ "System.Boolean" => GetGenericParseExpression(SourceExpression),
+ "System.Char" => GetGenericParseExpression(SourceExpression),
+ _ => throw new ArgumentException(string.Format("Conversion from {0} to {1} is not supported", "String", TargetType)),
+ };
+ if (Nullable.GetUnderlyingType(TargetType) == null)
{
- MethodInfo ParseMetod = type.GetMethod("Parse", new[] { typeof(string) });
- MethodCallExpression CallExpression = Expression.Call(ParseMetod, new[] { sourceExpression });
- return CallExpression;
+ return valueExp;
}
- Expression GetDateTimeParseExpression(Expression sourceExpression, Type type, CultureInfo culture)
+ else
{
- MethodInfo ParseMetod = type.GetMethod("Parse", new[] { typeof(string), typeof(DateTimeFormatInfo) });
- ConstantExpression ProviderExpression = Expression.Constant(culture.DateTimeFormat, typeof(DateTimeFormatInfo));
- MethodCallExpression CallExpression = Expression.Call(ParseMetod, new[] { sourceExpression, ProviderExpression });
- return CallExpression;
+ //Convert to nullable if necessary
+ return Expression.Convert(valueExp, TargetType);
}
+ }
+ Expression GetGenericParseExpression<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
+#endif
+ T>(Expression sourceExpression)
+ {
+ MethodInfo ParseMetod = typeof(T).GetMethod("Parse", [typeof(string)])!;
+ MethodCallExpression CallExpression = Expression.Call(ParseMetod, [sourceExpression]);
+ return CallExpression;
+ }
+ Expression GetDateTimeParseExpression(Expression sourceExpression, CultureInfo culture)
+ {
+ MethodInfo ParseMetod = typeof(DateTime).GetMethod("Parse", [typeof(string), typeof(DateTimeFormatInfo)])!;
+ ConstantExpression ProviderExpression = Expression.Constant(culture.DateTimeFormat, typeof(DateTimeFormatInfo));
+ MethodCallExpression CallExpression = Expression.Call(ParseMetod, [sourceExpression, ProviderExpression]);
+ return CallExpression;
+ }
- MethodCallExpression GetEnumParseExpression(Expression sourceExpression, Type type)
- {
- //Get the MethodInfo for parsing an Enum
- MethodInfo EnumParseMethod = typeof(Enum).GetMethod("Parse", new[] { typeof(Type), typeof(string), typeof(bool) });
- ConstantExpression TargetMemberTypeExpression = Expression.Constant(type);
- ConstantExpression IgnoreCase = Expression.Constant(true, typeof(bool));
- //Create an expression the calls the Parse method
- MethodCallExpression CallExpression = Expression.Call(EnumParseMethod, new[] { TargetMemberTypeExpression, sourceExpression, IgnoreCase });
- return CallExpression;
- }
- MethodCallExpression GetNumberParseExpression(Expression sourceExpression, Type type, CultureInfo culture)
- {
- MethodInfo ParseMetod = type.GetMethod("Parse", new[] { typeof(string), typeof(NumberFormatInfo) });
- ConstantExpression ProviderExpression = Expression.Constant(culture.NumberFormat, typeof(NumberFormatInfo));
- MethodCallExpression CallExpression = Expression.Call(ParseMetod, new[] { sourceExpression, ProviderExpression });
- return CallExpression;
- }
- }
- static MethodInfo changeType = typeof(Convert).GetMethod("ChangeType", [typeof(object), typeof(Type)])!;
- static MethodInfo isNullOrEmpty = typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!;
- private static Expression ConvertTypeExpression(Expression source, Type sourceType, Type targetType)
+ MethodCallExpression GetEnumParseExpression(Expression sourceExpression, Type type)
{
- var underType = Nullable.GetUnderlyingType(targetType) ?? targetType;
- var isNull = Expression.Equal(source, Expression.Constant(null));
- var stringValue = Expression.Call(source, sourceType.GetMethod("ToString", Type.EmptyTypes)!);
- var isNullOrEmptyExpression = Expression.Call(isNullOrEmpty, stringValue);
- var canConvert = Expression.AndAlso(Expression.IsFalse(isNull), Expression.IsFalse(isNullOrEmptyExpression));
- var finalValue = Expression.Convert(Expression.Call(changeType, source, Expression.Constant(underType)), targetType);
- return Expression.Condition(canConvert, finalValue, Expression.Default(targetType));
+ //Get the MethodInfo for parsing an Enum
+ MethodInfo EnumParseMethod = typeof(Enum).GetMethod("Parse", [typeof(Type), typeof(string), typeof(bool)])!;
+ ConstantExpression TargetMemberTypeExpression = Expression.Constant(type);
+ ConstantExpression IgnoreCase = Expression.Constant(true, typeof(bool));
+ //Create an expression the calls the Parse method
+ MethodCallExpression CallExpression = Expression.Call(EnumParseMethod, [TargetMemberTypeExpression, sourceExpression, IgnoreCase]);
+ return CallExpression;
+ }
+
+// MethodCallExpression GetNumberParseExpression(Expression sourceExpression,
+//#if NET8_0_OR_GREATER
+// [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
+//#endif
+// Type type, CultureInfo culture)
+// {
+// MethodInfo ParseMetod = type.GetMethod("Parse", [typeof(string), typeof(NumberFormatInfo)])!;
+// ConstantExpression ProviderExpression = Expression.Constant(culture.NumberFormat, typeof(NumberFormatInfo));
+// MethodCallExpression CallExpression = Expression.Call(ParseMetod, [sourceExpression, ProviderExpression]);
+// return CallExpression;
+// }
+ MethodCallExpression NumberParseExpression<
+#if NET8_0_OR_GREATER
+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)]
+#endif
+ T>(Expression source, CultureInfo culture)
+ {
+ MethodInfo ParseMetod = typeof(T).GetMethod("Parse", [typeof(string), typeof(NumberFormatInfo)])!;
+ ConstantExpression ProviderExpression = Expression.Constant(culture.NumberFormat, typeof(NumberFormatInfo));
+ MethodCallExpression CallExpression = Expression.Call(ParseMetod, [source, ProviderExpression]);
+ return CallExpression;
}
}
+
+ static MethodInfo changeType = typeof(Convert).GetMethod("ChangeType", [typeof(object), typeof(Type)])!;
+ static MethodInfo isNullOrEmpty = typeof(string).GetMethod(nameof(string.IsNullOrEmpty))!;
+ private static ConditionalExpression ConvertTypeExpression(Expression source, Type sourceType, Type targetType)
+ {
+ var underType = Nullable.GetUnderlyingType(targetType) ?? targetType;
+ var isNull = Expression.Equal(source, Expression.Constant(null));
+ var stringValue = Expression.Call(source, typeof(Convert).GetMethod("ToString", [sourceType])!);
+ var isNullOrEmptyExpression = Expression.Call(isNullOrEmpty, stringValue);
+ var canConvert = Expression.AndAlso(Expression.IsFalse(isNull), Expression.IsFalse(isNullOrEmptyExpression));
+ var finalValue = Expression.Convert(Expression.Call(changeType, source, Expression.Constant(underType)), targetType);
+ return Expression.Condition(canConvert, finalValue, Expression.Default(targetType));
+
+ }
}
diff --git a/src/Toolkit/ExpressionHelper/ExpressionCombine.cs b/src/Toolkit/ExpressionHelper/ExpressionCombine.cs
index dcb3b87..7ac0c24 100644
--- a/src/Toolkit/ExpressionHelper/ExpressionCombine.cs
+++ b/src/Toolkit/ExpressionHelper/ExpressionCombine.cs
@@ -7,8 +7,18 @@
namespace MT.Toolkit.ExpressionHelper
{
+ ///
+ /// 表达式操作
+ ///
public static class ExpressionCombine
{
+ ///
+ /// 使用连接两个表达式树
+ ///
+ ///
+ ///
+ ///
+ ///
public static Expression> AndAlso(this Expression> self, Expression> other)
{
var p = self.Parameters;
@@ -16,6 +26,14 @@ public static Expression> AndAlso(this Expression
return Expression.Lambda>(body, p);
}
+ ///
+ /// 使用连接两个表达式树
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
public static Expression> AndAlsoIf(this Expression> self, bool condition, Expression> other)
{
if (!condition) return self;
@@ -24,6 +42,14 @@ public static Expression> AndAlsoIf(this Expression>(body, p);
}
+ ///
+ /// 使用连接两个表达式树
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
public static Expression> AndAlsoIf(this Expression> self, Func condition, Expression> other)
{
if (!condition.Invoke()) return self;
@@ -32,6 +58,13 @@ public static Expression> AndAlsoIf(this Expression>(body, p);
}
+ ///
+ /// 使用连接两个表达式树
+ ///
+ ///
+ ///
+ ///
+ ///
public static Expression> OrElse(this Expression> self, Expression> other)
{
var p = self.Parameters;
@@ -39,6 +72,14 @@ public static Expression> OrElse(this Expression>
return Expression.Lambda>(body, p);
}
+ ///
+ /// 使用连接两个表达式树
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
public static Expression> OrElseIf(this Expression> self, bool condition, Expression> other)
{
if (!condition) return self;
@@ -46,6 +87,15 @@ public static Expression> OrElseIf(this Expression>(body, p);
}
+
+ ///
+ /// 使用连接两个表达式树
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
public static Expression> OrElseIf(this Expression> self, Func condition, Expression> other)
{
if (!condition.Invoke()) return self;
diff --git a/src/Toolkit/FrequencyGuard/Debounce.cs b/src/Toolkit/FrequencyGuard/Debounce.cs
new file mode 100644
index 0000000..99709f9
--- /dev/null
+++ b/src/Toolkit/FrequencyGuard/Debounce.cs
@@ -0,0 +1,150 @@
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MT.Toolkit;
+
+///
+/// 防抖器
+///
+public class Debounce : IDisposable
+{
+ private CancellationTokenSource? cts = null;
+ private readonly Func action;
+ private readonly int delayMs;
+
+ private Debounce(Action action, int delayMs)
+ {
+ this.action = (value, _) =>
+ {
+ action(value);
+ return Task.CompletedTask;
+ };
+ this.delayMs = delayMs;
+ }
+
+ private Debounce(Func action, int delayMs)
+ {
+ this.action = action;
+ this.delayMs = delayMs;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task InvokeAsync(T value, CancellationToken cancellationToken = default)
+ {
+ cts?.Cancel();
+ cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ var token = cts.Token;
+ try
+ {
+ await Task.Delay(delayMs, token);
+ if (!token.IsCancellationRequested)
+ {
+ await action(value, token);
+ return true;
+ }
+ return false;
+ }
+ catch (OperationCanceledException)
+ {
+ return false;
+ }
+ }
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Debounce Create(Action action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Debounce Create(Func action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ ///
+ ///
+ public void Dispose()
+ {
+ cts?.Dispose();
+ GC.SuppressFinalize(this);
+ }
+}
+
+///
+/// 无参防抖器
+///
+public class Debounce : IDisposable
+{
+ private CancellationTokenSource? cts = null;
+ private readonly Func action;
+ private readonly int delayMs;
+
+ private Debounce(Action action, int delayMs)
+ {
+ this.action = _ =>
+ {
+ action();
+ return Task.CompletedTask;
+ };
+ this.delayMs = delayMs;
+ }
+
+ private Debounce(Func action, int delayMs)
+ {
+ this.action = action;
+ this.delayMs = delayMs;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ public async Task InvokeAsync(CancellationToken cancellationToken = default)
+ {
+ cts?.Cancel();
+ cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ var token = cts.Token;
+ try
+ {
+ await Task.Delay(delayMs, token);
+ if (!token.IsCancellationRequested)
+ {
+ await action(token);
+ return true;
+ }
+ return false;
+ }
+ catch (OperationCanceledException)
+ {
+ return false;
+ }
+ }
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Debounce Create(Action action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Debounce Create(Func action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ ///
+ ///
+ public void Dispose()
+ {
+ cts?.Dispose();
+ GC.SuppressFinalize(this);
+ }
+}
\ No newline at end of file
diff --git a/src/Toolkit/FrequencyGuard/Throttle.cs b/src/Toolkit/FrequencyGuard/Throttle.cs
new file mode 100644
index 0000000..c92c49b
--- /dev/null
+++ b/src/Toolkit/FrequencyGuard/Throttle.cs
@@ -0,0 +1,158 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace MT.Toolkit;
+
+///
+/// 节流器
+///
+public class Throttle : IDisposable
+{
+ private readonly SemaphoreSlim semaphoreSlim = new(1, 1);
+ private readonly Func action;
+ private readonly int delayMs;
+
+ private Throttle(Action action, int delayMs)
+ {
+ this.action = (value, _) =>
+ {
+ action(value);
+ return Task.CompletedTask;
+ };
+ this.delayMs = delayMs;
+ }
+
+ private Throttle(Func action, int delayMs)
+ {
+ this.action = action;
+ this.delayMs = delayMs;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task InvokeAsync(T value, CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ if (!await semaphoreSlim.WaitAsync(0, cancellationToken))
+ return false;
+ _ = ReleaseSemaphore(semaphoreSlim, delayMs);
+ await action(value, cancellationToken).ConfigureAwait(false);
+ return true;
+ }
+ catch (Exception)
+ {
+ throw;
+ }
+ }
+
+ private static async Task ReleaseSemaphore(SemaphoreSlim semaphore, int ms)
+ {
+ await Task.Delay(ms).ConfigureAwait(false);
+ semaphore.Release();
+ }
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Throttle Create(Action action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Throttle Create(Func action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ ///
+ ///
+ public void Dispose()
+ {
+ semaphoreSlim.Dispose();
+ GC.SuppressFinalize(this);
+ }
+}
+
+
+///
+/// 无参节流器
+///
+public class Throttle : IDisposable
+{
+ private readonly SemaphoreSlim semaphoreSlim = new(1, 1);
+ private readonly Func action;
+ private readonly int delayMs;
+
+ private Throttle(Action action, int delayMs)
+ {
+ this.action = _ =>
+ {
+ action();
+ return Task.CompletedTask;
+ };
+ this.delayMs = delayMs;
+ }
+
+ private Throttle(Func action, int delayMs)
+ {
+ this.action = action;
+ this.delayMs = delayMs;
+ }
+
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task InvokeAsync(CancellationToken cancellationToken = default)
+ {
+ try
+ {
+ if (!await semaphoreSlim.WaitAsync(0, cancellationToken))
+ return false;
+ _ = ReleaseSemaphore(semaphoreSlim, delayMs);
+ await action(cancellationToken).ConfigureAwait(false);
+ return true;
+ }
+ catch (Exception)
+ {
+ throw;
+ }
+ }
+
+ private static async Task ReleaseSemaphore(SemaphoreSlim semaphore, int ms)
+ {
+ await Task.Delay(ms).ConfigureAwait(false);
+ semaphore.Release();
+ }
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Throttle Create(Action action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ /// 创建一个防抖器
+ ///
+ public static Throttle Create(Func action, int delayMs)
+ => new(action, delayMs);
+
+ ///
+ ///
+ ///
+ public void Dispose()
+ {
+ semaphoreSlim.Dispose();
+ GC.SuppressFinalize(this);
+ }
+}
diff --git a/src/Toolkit/HttpHelper/ISoapServiceManager.cs b/src/Toolkit/HttpHelper/ISoapServiceManager.cs
index 9aae5f9..247c105 100644
--- a/src/Toolkit/HttpHelper/ISoapServiceManager.cs
+++ b/src/Toolkit/HttpHelper/ISoapServiceManager.cs
@@ -1,26 +1,27 @@
using System;
using System.Collections.Concurrent;
-namespace MT.Toolkit.HttpHelper
+namespace MT.Toolkit.HttpHelper;
+
+///
+/// SOAP服务配置器
+///
+#pragma warning disable
+[Obsolete("please use LoggerProviderExtensions instead.")]
+public interface ISoapServiceManager
{
+ internal ConcurrentDictionary Configs { get; }
+ internal string? DefaultKey { get; }
///
- /// SOAP服务配置器
+ /// 设置默认的KEY
///
- public interface ISoapServiceManager
- {
- internal ConcurrentDictionary Configs { get; }
- internal string? DefaultKey { get; }
- ///
- /// 设置默认的KEY
- ///
- ///
- ///
- ISoapServiceManager SetDefault(string key);
- ///
- /// 添加SOAP服务
- ///
- /// 配置名称
- ///
- ///
- ISoapServiceManager AddSoapService(string name, Action config);
- }
+ ///
+ ///
+ ISoapServiceManager SetDefault(string key);
+ ///
+ /// 添加SOAP服务
+ ///
+ /// 配置名称
+ ///
+ ///
+ ISoapServiceManager AddSoapService(string name, Action config);
}
\ No newline at end of file
diff --git a/src/Toolkit/HttpHelper/SoapFaultException.cs b/src/Toolkit/HttpHelper/SoapFaultException.cs
index 54f8e45..39500ef 100644
--- a/src/Toolkit/HttpHelper/SoapFaultException.cs
+++ b/src/Toolkit/HttpHelper/SoapFaultException.cs
@@ -6,9 +6,24 @@
namespace MT.Toolkit.HttpHelper;
+///
+/// Soap接口调用异常类
+///
+///
+///
+///
public class SoapFaultException(string? fCode, string? fString, string? fDetail) : Exception($"{fCode}-{fString}-{fDetail}")
{
+ ///
+ /// Gets the fault code associated with the current error, if available.
+ ///
public string? FaultCode { get; } = fCode;
+ ///
+ /// Gets the fault string associated with the current error, if available.
+ ///
public string? FaultString { get; } = fString;
+ ///
+ /// Gets the fault detail associated with the current error, if available.
+ ///
public string? FaultDetail { get; } = fDetail;
}
diff --git a/src/Toolkit/HttpHelper/SoapResponse.cs b/src/Toolkit/HttpHelper/SoapResponse.cs
index 7356d63..69fb95b 100644
--- a/src/Toolkit/HttpHelper/SoapResponse.cs
+++ b/src/Toolkit/HttpHelper/SoapResponse.cs
@@ -1,247 +1,241 @@
using MT.Toolkit.TypeConvertHelper;
using MT.Toolkit.XmlHelper;
using System;
-using System.Collections;
using System.Collections.Generic;
using System.Data;
-using System.Data.SqlTypes;
-using System.Dynamic;
using System.IO;
using System.Linq;
-using System.Linq.Expressions;
using System.Xml;
using System.Xml.Linq;
-using System.Xml.XPath;
-namespace MT.Toolkit.HttpHelper
+namespace MT.Toolkit.HttpHelper;
+
+#pragma warning disable
+
+[Obsolete("Use SoapRequestHelper Package instead.", true)]
+public sealed class SoapResponse
{
- [Obsolete("Use SoapRequestHelper Package instead.", true)]
- public sealed class SoapResponse
- {
- public const string RN_ALIAS = "r";
- ///
- /// 请求是否发送成功
- ///
- public bool Success { get; set; } = true;
- ///
- /// 请求发生异常时的异常
- ///
- public Exception? Exception { get; set; }
- ///
- /// 请求发生异常或解析返回数据时发生异常的异常信息
- ///
- public string? Message { get; set; }
- private readonly XmlString? xmlString;
- private readonly string? responseContent;
- private XmlNamespaceManager? nsManager;
- private readonly string? methodName;
+ public const string RN_ALIAS = "r";
+ ///
+ /// 请求是否发送成功
+ ///
+ public bool Success { get; set; } = true;
+ ///
+ /// 请求发生异常时的异常
+ ///
+ public Exception? Exception { get; set; }
+ ///
+ /// 请求发生异常或解析返回数据时发生异常的异常信息
+ ///
+ public string? Message { get; set; }
+ private readonly XmlString? xmlString;
+ private readonly string? responseContent;
+ private XmlNamespaceManager? nsManager;
+ private readonly string? methodName;
- internal SoapResponse(string requestContent, string? responseContent, string? rawValue, XmlNamespaceManager manager, string? methodName)
- {
- RequestContent = requestContent;
- this.responseContent = responseContent;
- xmlString = rawValue;
- nsManager = manager;
- this.methodName = methodName;
- }
+ internal SoapResponse(string requestContent, string? responseContent, string? rawValue, XmlNamespaceManager manager, string? methodName)
+ {
+ RequestContent = requestContent;
+ this.responseContent = responseContent;
+ xmlString = rawValue;
+ nsManager = manager;
+ this.methodName = methodName;
+ }
- internal SoapResponse(string requestContent,string? responseContent, Exception ex)
- {
- Success = false;
- RequestContent = requestContent;
- this.responseContent = responseContent;
- Exception = ex;
- Message = ex.Message;
- }
- public string? RawContent => responseContent;
- public string? RawValue => xmlString?.Value;
- public string RequestContent { get; }
- private XElement? retXml;
+ internal SoapResponse(string requestContent,string? responseContent, Exception ex)
+ {
+ Success = false;
+ RequestContent = requestContent;
+ this.responseContent = responseContent;
+ Exception = ex;
+ Message = ex.Message;
+ }
+ public string? RawContent => responseContent;
+ public string? RawValue => xmlString?.Value;
+ public string RequestContent { get; }
+ private XElement? retXml;
- #region 解析返回值
- ///
- /// 接口签名中return的内容
- ///
- ///
- ///
- public T? ReadReturnValue()
+ #region 解析返回值
+ ///
+ /// 接口签名中return的内容
+ ///
+ ///
+ ///
+ public T? ReadReturnValue()
+ {
+ var type = typeof(T);
+ if (type != typeof(object))
{
- var type = typeof(T);
- if (type != typeof(object))
- {
- var str = xmlString?.GetValue($"//{RN_ALIAS}:{methodName}Result", nsManager);
- if (string.IsNullOrEmpty(str)) return default;
- var ret = Convert.ChangeType(str, typeof(T));
- if (ret == null) return default;
- return (T?)ret;
- }
- // 序列化返回的结果
- return GetNode($"//{RN_ALIAS}:{methodName}Result")?.AsDynamic();
+ var str = xmlString?.GetValue($"//{RN_ALIAS}:{methodName}Result", nsManager);
+ if (string.IsNullOrEmpty(str)) return default;
+ var ret = Convert.ChangeType(str, typeof(T));
+ if (ret == null) return default;
+ return (T?)ret;
}
- ///
- /// 接口签名中return的内容
- ///
- ///
- ///
- public dynamic? ReadReturnValue() => ReadReturnValue