![]() |
VOOZH | about |
dotnet add package Azrng.Core --version 1.19.0
NuGet\Install-Package Azrng.Core -Version 1.19.0
<PackageReference Include="Azrng.Core" Version="1.19.0" />
<PackageVersion Include="Azrng.Core" Version="1.19.0" />Directory.Packages.props
<PackageReference Include="Azrng.Core" />Project file
paket add Azrng.Core --version 1.19.0
#r "nuget: Azrng.Core, 1.19.0"
#:package Azrng.Core@1.19.0
#addin nuget:?package=Azrng.Core&version=1.19.0Install as a Cake Addin
#tool nuget:?package=Azrng.Core&version=1.19.0Install as a Cake Tool
💎 高效、可靠的.NET核心工具库 - 为您的应用提供通用扩展方法和帮助类
通过 NuGet 安装:
Install-Package Azrng.Core
或通过 .NET CLI:
dotnet add package Azrng.Core
// 判断字符串类型
bool isInt = "123".IsIntFormat(); // true
bool isDecimal = "123.45".IsDecimalFormat(); // true
bool isDate = "2024-01-01".IsDateFormat(); // true
bool hasChinese = "你好".HasChinese(); // true
// 字符串验证
bool isNullOrEmpty = "".IsNullOrEmpty(); // true
bool isNotNullOrWhiteSpace = " ".IsNotNullOrWhiteSpace(); // false
// 字符串操作
string[] array = "a,b,c".ToStrArray(); // ["a", "b", "c"]
string indexed = "Hello".GetByIndex(1); // "e"
bool equals = "hello".EqualsNoCase("HELLO"); // true
var list = new List<int> { 1, 2, 3, 4, 5 };
// 判断集合
bool isNullOrEmpty = list.IsNullOrEmpty(); // false
bool isNotNullOrEmpty = list.IsNotNullOrEmpty(); // true
// 条件过滤
var filtered = list.WhereIF(true, x => x > 2); // [3, 4, 5]
var filtered2 = list.WhereIF(false, x => x > 2); // [1, 2, 3, 4, 5]
// 分页
var page = list.ToPage(1, 2); // [1, 2]
var pageList = list.ToPageList(2, 2); // [3, 4]
// 带索引遍历
foreach (var (item, index) in list.WithIndex())
{
Console.WriteLine($"{index}: {item}");
}
// 添加如果不存在
list.AddIfNotContains(6); // 添加成功
list.AddIfNotContains(1); // 添加失败(已存在)
var now = DateTime.Now;
// 格式化
string standard = now.ToStandardString(); // "2024-01-01 12:00:00"
string dateOnly = now.ToDateString(); // "2024-01-01"
string iso = now.ToIsoDateTimeString(); // "2024-01-01T12:00:00.0000000"
string detailed = now.ToDetailedTimeString(); // "2024-01-01 12:00:00.0000000"
// 可空类型支持
DateTime? nullableDate = now;
string fromNullable = nullableDate.ToStandardString(); // "2024-01-01 12:00:00"
// 自定义格式
string custom = now.ToFormatString("yyyy年MM月dd日"); // "2024年01月01日"
// 对象转 URL 参数
var user = new UserInfoDto { Id = 1, Name = "Test" };
string url = user.ToUrlParameter(); // "Id=1&Name=Test"
string urlLower = user.ToUrlParameter(true); // "id=1&name=test"
// 对象转字典
var dict = user.ToDictionary(); // {"Id": "1", "Name": "Test"}
var dictLower = user.ToDictionary(true); // {"id": "1", "name": "Test"}
// 类型转换
int value = "123".To<int, int>(0); // 123
DateTime date = "2024-01-01".To<string, DateTime>(DateTime.MinValue);
public enum Status
{
[Description("激活")]
Active,
[Description("停用")]
Inactive
}
// 获取描述
string description = Status.Active.GetDescription(); // "激活"
// 枚举帮助类
var enumDict = EnumHelper.EnumToDictionary<Status>();
// 结果: {0: "激活", 1: "停用"}
var keys = EnumHelper.GetKeys<Status>();
// 结果: ["Active", "Inactive"]
var values = EnumHelper.GetValues<Status>();
// 结果: [0, 1]
Status value = EnumHelper.GetEnumValue<Status>("激活"); // Status.Active
decimal price = 1234.5678m;
// 格式化
string standard = price.ToStandardString(2); // "1234.57"(四舍五入)
string noZero = price.ToNoZeroString(2); // "1234.57"(不保留末尾0)
string fixed = price.ToFixedString(3); // "1234.568"(保留末尾0)
// 取绝对值
decimal abs = (-123.45m).ToAbs(); // 123.45
byte[] data = new byte[] { 0x01, 0x02, 0x03 };
// 转换
string hex = data.ToHexString(); // "010203"
string base64 = data.ToBase64(); // "AQID"
Stream stream = data.ToStream(); // 转为流
int number = new byte[] { 0x01, 0x00, 0x00, 0x00 }.ToInt32(); // 1
// 文件类型检测
byte[] fileBytes = File.ReadAllBytes("test.jpg");
string? contentType = fileBytes.GetContentType(); // "image/jpeg"
string? suffix = fileBytes.GetFileSuffix(); // ".jpg"
var dict = new Dictionary<string, string>
{
["name"] = "张三",
["age"] = "25"
};
// 获取值或默认值
string name = dict.GetOrDefault("name", "默认值"); // "张三"
string email = dict.GetOrDefault("email", ""); // ""
// 根据列名获取值
string value = dict.GetColumnValueByName("name"); // "张三"
var sb = new StringBuilder();
// 条件追加
sb.AppendIF(true, "Hello"); // 追加
sb.AppendIF(false, "World"); // 不追加
sb.AppendLineIF(true, "Line"); // 追加并换行
// 非空追加
sb.AppendIfNotEmpty("Not Null"); // 追加
sb.AppendIfNotEmpty(null); // 不追加
sb.AppendLineIfNotNullOrWhiteSpace("Text"); // 追加并换行
// 常用验证
bool isIdCard = "110101199001011234".IsIdCard(); // true
bool isPhone = "13800138000".IsPhone(); // true
bool isEmail = "test@example.com".IsEmail(); // true
bool isUrl = "https://example.com".IsUrl(); // true
bool isIP = "192.168.1.1".IsIPAddress(); // true
// 正则匹配
bool isMatch = "test123".IsMatch(@"\d+"); // true
// 转义为正则表达式
string escaped = "test.exe".ToRegex(); // "test\.exe"
try
{
// 可能抛出异常的代码
}
catch (Exception ex)
{
string errorInfo = ex.GetExceptionAndStack();
// "message:错误消息 stackTrace:堆栈跟踪 innerException:内部异常"
}
// 成功结果,保留业务消息
var success = ResultModelFactory.Success(new[] { "A", "B" }, "加载成功");
// 失败结果,指定错误码
var failure = ResultModelFactory.Failure<string>("参数错误", "400");
// Azrng 异常转换为失败结果时会保留 ErrorCode
try
{
throw new LogicBusinessException("业务规则不满足");
}
catch (Exception ex)
{
IResultModel<bool> result = ex.ToFailureResult<bool>();
}
// 普通异常如需隐藏内部细节,可传入对外消息
var safeResult = new InvalidOperationException("internal details")
.ToFailureResult<bool>("操作失败");
// 安全读取数据,避免调用方重复处理 null
IResultModel<List<int>> listResult = ResultModel<List<int>>.Failure("查询失败");
List<int> rows = listResult.DataOrEmpty();
IResultModel<string> valueResult = ResultModel<string>.Failure("查询失败");
string value = valueResult.DataOrDefault("默认值");
var random = new Random();
// 随机小数
double rnd = random.NextDouble(1.0, 10.0); // 1.0 ~ 10.0
// 随机选择
var list = new List<string> { "A", "B", "C", "D" };
string item = random.NextItem(list); // 随机返回一个
var items = random.NextItems(list, 2); // 随机返回两个
var query = context.Users.AsQueryable();
// 动态排序
var sorted = query.OrderBy(x => x.Name, true); // 升序
var sorted2 = query.OrderBy(x => x.Name, false); // 降序
// 根据字符串排序
var sorted3 = query.OrderBy("Name", true); // 升序
// 查询映射
var dtos = query.SelectMapper<UserDto>(); // 自动映射属性
// 类型判断
bool IsIntFormat(this string str) // 判断是否是整数
bool IsDecimalFormat(this string str) // 判断是否是decimal
bool IsDateFormat(this string str) // 判断是否是日期
bool HasChinese(this string str) // 判断是否包含中文
// 空值判断
bool IsNullOrEmpty(this string currentString) // 是 null 或空
bool IsNotNullOrEmpty(this string currentString) // 不是 null 或空
bool IsNullOrWhiteSpace(this string currentString) // 是 null/空/空白
bool IsNotNullOrWhiteSpace(this string currentString) // 不是 null/空/空白
// 字符串操作
string[] ToStrArray(this string str, string separator = ",") // 分割成数组
StringBuilder AppendIF(this StringBuilder builder, bool condition, string str) // 条件拼接
string GetByIndex(this string str, int index) // 获取特定位置字符
bool EqualsNoCase(this string aimStr, string comparaStr) // 忽略大小写比较
bool IsNullOrEmpty<T>(this IEnumerable<T>? source) // 是 null 或空
bool IsNotNullOrEmpty<T>(this IEnumerable<T>? source) // 不是 null 或空
IEnumerable<T> WhereIF<T>(this IEnumerable<T>? source, bool condition, Func<T, bool> predicate) // 条件过滤
IEnumerable<T> ToPage<T>(this IEnumerable<T>? source, int pageIndex, int pageSize) // 分页
List<T> ToPageList<T>(this IEnumerable<T>? source, int pageIndex, int pageSize) // 分页转List
T[] ToPageArray<T>(this IEnumerable<T>? source, int pageIndex, int pageSize) // 分页转Array
Dictionary<string, string> AsciiDictionary(this Dictionary<string, string> dic) // ASCII排序
IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> source) // 带索引遍历
bool AddIfNotContains<T>(this ICollection<T> source, T item) // 如果不存在则添加
// 格式化方法
string ToStandardString(this DateTime time) // "yyyy-MM-dd HH:mm:ss"
string ToStandardString(this DateTime? time) // 可空版本
string ToDateString(this DateTime time) // "yyyy-MM-dd"
string ToDateString(this DateTime? time) // 可空版本
string ToIsoDateTimeString(this DateTime dateTime) // ISO 8601 格式
string ToIsoDateTimeString(this DateTime? dateTime) // 可空版本
string ToDetailedTimeString(this DateTime time) // "yyyy-MM-dd HH:mm:ss.fffffff"
string ToDetailedTimeString(this DateTime? time) // 可空版本
string ToFormatString(this DateTime time, string format) // 自定义格式
string ToUrlParameter<T>(this T source, bool paramLower = false) // 转URL参数
Dictionary<string, string> ToDictionary<T>(this T source, bool paramLower = false) // 转字典
TTo To<TFrom, TTo>(this TFrom from, TTo defaultValue) // 类型转换
string? UrlEncode(this string? target) // URL编码
string? UrlEncode(this string? target, Encoding encoding) // 指定编码
string? UrlDecode(this string? target) // URL解码
string? UrlDecode(this string? target, Encoding encoding) // 指定编码
string AttributeEncode(this string target) // HTML属性编码
string HtmlEncode(this string target) // HTML编码
string HtmlDecode(this string target) // HTML解码
string GetDescription(this Enum value) // 获取Description特性
string GetEnglishDescription(this Enum value) // 获取英文描述
// 查询映射
IQueryable<Tm> SelectMapper<T, Tm>(this IQueryable<T> queryable) // 查询映射
// 排序
IQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> query, Expression<Func<TSource, TKey>> keySelector, bool isAsc) // 根据条件排序
IQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> query, Expression<Func<TSource, TKey>> keySelector, SortEnum sortEnum) // 根据枚举排序
IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> query, params SortContent[] orderContent) // 多列排序
IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> query, SortContent orderContent) // 单列排序
IQueryable<T> OrderBy<T>(this IQueryable<T> queryable, string sortField, bool isAsc) // 根据字段名排序
// 转换方法
string ToHexString(this byte[] bytes) // 转十六进制字符串
string ToBase64(this byte[] bytes) // 转Base64字符串
Stream ToStream(this byte[] bytes) // 转为Stream
int ToInt32(this byte[] data) // 转为int32
// 文件操作
string? GetFileSuffix(this byte[] bytes) // 获取文件后缀
string? GetContentType(this byte[] bytes) // 获取Content-Type
string? GetFileCode(this byte[] bytes) // 获取文件编码
TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue>? dictionary, TKey key, TValue defaultValue) // 获取或返回默认值
string? GetColumnValueByName(this IDictionary<string, string>? keyValues, string? key) // 获取string列值
string GetColumnValueByName(this IDictionary<string, object?>? keyValues, string? key) // 获取object列值
T? GetColumnValueByName<T>(this IDictionary<string, object?>? keyValues, string? key) // 获取指定类型列值
// 格式化
string ToStandardString(this decimal dec, int number = 2) // 转标准格式(四舍五入)
string ToStandardString(this decimal? dec, int number = 2) // 可空版本
string ToNoZeroString(this decimal dec, int number = 2) // 不保留小数点后的0
string ToNoZeroString(this decimal? dec, int number = 2) // 可空版本
string ToFixedString(this decimal dec, int number = 2) // 保留几位小数(保留结尾0)
string ToFixedString(this decimal? dec, int number = 2) // 可空版本
// 运算
decimal ToAbs(this decimal @decimal) // 取绝对值
// 格式化
string ToStandardString(this double dec, int number = 2) // 转标准格式(四舍五入)
string ToStandardString(this double? dec, int number = 2) // 可空版本
string ToNoZeroString(this double dec, int number = 2) // 不保留小数点后的0
string ToNoZeroString(this double? dec, int number = 2) // 可空版本
string ToFixedString(this double dec, int number = 2) // 保留几位小数(保留结尾0)
string ToFixedString(this double? dec, int number = 2) // 可空版本
// 运算
double ToAbs(this double @decimal) // 取绝对值
// 条件拼接
StringBuilder AppendIF(this StringBuilder builder, bool condition, string? str) // 条件追加
StringBuilder AppendLineIF(this StringBuilder builder, bool condition, string? str) // 条件追加并换行
StringBuilder AppendFormatIF(this StringBuilder builder, bool condition, string format, params object[] args) // 条件格式化追加
// 非空判断追加
StringBuilder AppendLineIfNotEmpty(this StringBuilder builder, string? str) // 追加并换行(如果不为空)
StringBuilder AppendLineIfNotNullOrWhiteSpace(this StringBuilder builder, string? str) // 追加并换行(如果不为空或空白)
StringBuilder AppendIfNotEmpty(this StringBuilder builder, string? str) // 追加(如果不为空)
StringBuilder AppendIfNotNullOrWhiteSpace(this StringBuilder builder, string? str) // 追加(如果不为空或空白)
// 正则操作
string ToRegex(this string value) // 转为正则表达式可识别字符串
bool IsMatch(this string input, string pattern, RegexOptions options) // 验证是否匹配
bool IsMatch(this string inputStr, string patternStr) // 验证是否匹配
bool IsMatch(this string inputStr, string patternStr, bool isIgnoreSpace, bool isIgnoreCase) // 验证是否匹配(带选项)
// 常用验证
bool IsIdCard(this string? idCard) // 验证身份证是否合法
bool IsPhone(this string? cellPhone) // 验证手机格式是否合法
bool IsEmail(this string? email) // 验证邮箱格式是否合法
bool IsUrl(this string? url) // 验证URL格式是否合法
bool IsIPAddress(this string? ip) // 验证IP地址格式是否合法
bool IsJArrayString(this string jsonStr) // 验证是否是JArray字符串
T? CustomAttributeCommon<T>(this Type sourceType, string? fieldName) where T : Attribute // 获取自定义特性
Dictionary<Enum, T> ToEnumAndAttributes<T>(this Type type) where T : Attribute // 获取枚举值和对应的特性
string GetExceptionAndStack(this Exception ex) // 获取异常详细信息包含堆栈
IReadOnlyList<T> DataOrEmpty<T>(this IResultModel<IReadOnlyList<T>> result) // 数据为空时返回空只读列表
List<T> DataOrEmpty<T>(this IResultModel<List<T>> result) // 数据为空时返回空列表
T DataOrDefault<T>(this IResultModel<T> result, T defaultValue) // 数据为空时返回默认值
IResultModel<T> ToFailureResult<T>(this Exception exception, string? message = null) // 异常转换为失败结果
double NextDouble(this Random random, double minValue, double maxValue) // 生成指定范围随机小数
T NextItem<T>(this Random random, IList<T> list) // 随机返回列表中的一项
IEnumerable<T> NextItems<T>(this Random random, IList<T> list, int count) // 随机返回列表中的多项
IEnumerable<T> Flatten<T>(this T node, Func<T, IEnumerable<T>> childrenSelector) // 将树结构展平为一维
IEnumerable<T> GetAncestors<T>(this T node, Func<T, T> parentSelector) // 获取所有祖先节点
IEnumerable<T> GetDescendants<T>(this T node, Func<T, IEnumerable<T>> childrenSelector) // 获取所有后代节点
void SortBy<T>(this IList<T> list, string propertyName, bool ascending = true) // 根据属性名排序
List<T> ToList<T>(this DataTable table) // DataTable转List
string GetMimeType(this string fileName) // 根据文件名获取MIME类型
string GetMimeType(this byte[] fileBytes) // 根据文件字节获取MIME类型
int GetAge(this DateTime birthDate) // 根据出生日期获取年龄
string GetChineseZodiac(this DateTime birthDate) // 获取生肖
string GetZodiacSign(this DateTime birthDate) // 获取星座
IEnumerable<Type> GetLoadableTypes(this Assembly assembly) // 获取可加载的类型
IEnumerable<T> GetInstances<T>(this Assembly assembly) // 获取程序集中所有T实例
string GetPropertyName<T>(Expression<Func<T, object>> expression) // 获取属性名称
string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> expression) // 获取属性名称
// 同步方法
void LogInformation(string message) // 记录信息日志
void LogWarning(string message) // 记录警告日志
void LogError(string message) // 记录错误日志
// 异步方法
Task WriteMyLogsAsync(string level, string message) // 异步记录日志
Task FlushAsync() // 立即写入当前队列中的日志
// 配置
CoreGlobalConfig.MinimumLevel = LogLevel.Warning; // 设置最小日志级别
CoreGlobalConfig.LogRetentionDays = 7; // 日志保留天数(默认7天)
使用示例:
// 基本使用
LocalLogHelper.LogInformation("这是一条信息日志");
LocalLogHelper.LogWarning("这是一条警告日志");
LocalLogHelper.LogError("这是一条错误日志");
// 异步使用
await LocalLogHelper.WriteMyLogsAsync("Info", "这是一条测试日志");
await LocalLogHelper.FlushAsync();
// 配置日志级别(只输出Warning及以上级别)
CoreGlobalConfig.MinimumLevel = LogLevel.Warning;
// 基本重试
Task<T> ExecuteAsync<T>(Func<Task<T>> func, int maxRetryCount = 3)
Task<T> ExecuteAsync<T>(Func<Task<T>> func, int maxRetryCount, TimeSpan delay)
Task<T> ExecuteAsync<T>(Func<Task<T>> func, int maxRetryCount, Func<int, TimeSpan> delayStrategy)
// 条件重试
IRetryContext<T> WhenCatch<TException>(IRetryContext<T> context) where TException : Exception
IRetryContext<T> WhenResult<T>(IRetryContext<T> context, Func<T, bool> predicate)
使用示例:
// 简单重试
var result = await RetryHelper.ExecuteAsync(() => GetDataAsync(), 3);
// 带延时重试
var result = await RetryHelper.ExecuteAsync(
() => GetDataAsync(),
3,
TimeSpan.FromSeconds(2)
);
// 指数退避重试
var result = await RetryHelper.ExecuteAsync(
() => GetDataAsync(),
3,
i => TimeSpan.FromSeconds(Math.Pow(2, i))
);
// 条件重试
var result = await RetryHelper.ExecuteAsync(() => GetDataAsync(), 3)
.WhenCatch<HttpRequestException>();
// 基于结果重试
var result = await RetryHelper.ExecuteAsync(() => GetDataAsync(), 3)
.WhenResult(data => data == null);
// 分页处理集合
Task<int> ExecuteCollectionInPagesAsync<T>(ICollection<T> collection, Func<ICollection<T>, int, Task<int>> processFunc, int pageSize = 5000)
// 批次执行
int ExecuteInBatches(int totalNumber, Func<int, int> processFunc, int batchSize = 1000)
Task<int> ExecuteInBatchesAsync(int totalNumber, Func<int, Task<int>> processFunc, int batchSize = 1000)
// 随机删除
T RemoveRandomItem<T>(IList<T> list)
T GetEnumValue<T>(string description) // 根据描述获取枚举值
Dictionary<int, string> EnumToDictionary<T>() where T : Enum // 枚举转字典
List<string> GetKeys<TEnum>() // 获取所有键
List<int> GetValues<TEnum>() // 获取所有值
string CompressText(string originStr) // 压缩文本
string TextToUnicode(string text) // 文本转Unicode
string UnicodeToText(string unicode) // Unicode转文本
string ReplaceWithDictionary(string input, Dictionary<string, string> replacements) // 批量替换
string ReplaceWithOrder(string input, Dictionary<string, string> replacements) // 有序批量替换
string FormatFileSize(long bytes) // 格式化文件大小
// 示例: 1024 -> "1.00 KB", 1048576 -> "1.00 MB"
string GetTimeDifferenceText(DateTime dateTime) // 获取时间差文本
// 示例: "刚刚", "5分钟前", "2小时前", "3天前"
T ConvertToTargetType<T>(object value) // 转换为目标类型
T? ConvertToTargetTypeOrNull<T>(object value) // 转换为目标类型(可空)
string AddQueryString(string url, Dictionary<string, string> queryString) // 添加查询字符串
string SortUrlParameters(string url) // 排序URL参数
string ExtractUrl(string url) // 提取URL
string GetTimeDifferenceText(DateTime dateTime) // 获取时间差文本
DateTime GetStartOfWeek(DateTime date) // 获取周开始
DateTime GetEndOfWeek(DateTime date) // 获取周结束
DateTime GetStartOfMonth(DateTime date) // 获取月开始
DateTime GetEndOfMonth(DateTime date) // 获取月结束
string GetLocalIPAddress() // 获取本机IP地址
string GetLocalIPv4Address() // 获取IPv4地址
string GetLocalIPv6Address() // 获取IPv6地址
bool IsValidIPAddress(string ipAddress) // 验证IP地址是否有效
long GetTotalMemory() // 获取总内存
long GetAvailableMemory() // 获取可用内存
long GetUsedMemory() // 获取已用内存
string GetOSInfo() // 获取操作系统信息
string GetMachineName() // 获取机器名
string GetApplicationVersion() // 获取应用版本
string GetRuntimeInfo() // 获取运行时信息
void RunSync(Func<Task> task) // 同步执行异步方法
T RunSync<T>(Func<Task<T>> task) // 同步执行异步方法(带返回值)
Task RunTimeLimitAsync(Func<Task> task, TimeSpan timeout) // 运行带时间限制的任务
Task<T> RunTimeLimitAsync<T>(Func<Task<T>> task, TimeSpan timeout) // 运行带时间限制的任务(带返回值)
void SetInterval(Action action, int interval) // 设置定时器
void SetTimeout(Action action, int delay) // 设置延迟执行
TimeSpan Time(Action action) // 计时执行操作
T Time<T>(Func<T> func) // 计时执行操作(带返回值)
byte[] Compress(byte[] data) // 压缩数据
byte[] Decompress(byte[] data) // 解压数据
string CompressString(string text) // 压缩字符串
string DecompressString(string compressedText) // 解压字符串
bool IsValidCronExpression(string cronExpression) // 验证Cron表达式是否有效
DateTime? GetNextOccurrence(string cronExpression, DateTime baseTime) // 获取下次执行时间
List<DateTime> GetNextOccurrences(string cronExpression, DateTime baseTime, int count) // 获取接下来的执行时间
string ToCsv<T>(List<T> data) // 转为CSV格式
List<T> FromCsv<T>(string csv) // 从CSV格式解析
string GetDbType(Type clrType) // 获取数据库类型
Type GetClrType(string dbType) // 获取CLR类型
string HtmlToText(string html) // HTML转纯文本
string StripHtml(string html) // 移除HTML标签
string EncodeHtml(string text) // HTML编码
string DecodeHtml(string html) // HTML解码
void EnsureDirectoryExists(string path) // 确保目录存在
void CopyDirectory(string source, destination) // 复制目录
void DeleteDirectory(string path, bool recursive) // 删除目录
void MoveDirectory(string source, destination) // 移动目录
string ToChineseNumber(int number) // 转中文数字
string ToChineseNumber(decimal number) // 转中文数字(小数)
string ToChineseCurrency(decimal number) // 转中文大写金额
string ToRMB(decimal amount) // 转人民币大写
string ToRMB(double amount) // 转人民币大写
bool HasSqlInjectionRisk(string input) // 检测SQL注入风险
string EscapeSqlString(string input) // 转义SQL字符串
string SanitizeSqlInput(string input) // 清理SQL输入
int GetChineseStringLength(string text) // 获取中文字符串长度
string GetChinesePinyin(string chinese) // 获取中文拼音
bool IsAllChinese(string text) // 是否全部是中文
void WriteInfoLine(string message) // 输出信息
void WriteWarningLine(string message) // 输出警告
void WriteErrorLine(string message) // 输出错误
void WriteSuccessLine(string message) // 输出成功
string? ReadLineWithPrompt(string prompt) // 带提示符读取输入
ConsoleKeyInfo ReadKeyWithPrompt(string prompt) // 带提示符读取按键
List<Assembly> GetAllAssemblies() // 获取所有程序集
List<Type> GetAllTypes() // 获取所有类型
List<Type> GetTypesWithInterface<T>() // 获取实现指定接口的类型
string GetChineseDate(DateTime date) // 获取中文日期
string GetChineseDayOfWeek(DateTime date) // 获取中文星期
bool IsLunarLeapMonth(int year, int month) // 是否是农历闰月
CommonHelper - 通用帮助方法GuardClause - 参数验证帮助类(Guard.Against.Null等)MimeExtensions - MIME类型扩展RandomExtensions - 随机数扩展TreeExtensions - 树结构扩展IListExtensions - IList扩展DataTableExtensions - DataTable扩展PersonExtensions - 个人信息扩展AssemblyExtensions - 程序集扩展ExpressExtensions - 表达式树扩展PredicateExtensions - 谓词扩展RetryTaskExtensions - 重试任务扩展封装了统一的返回结果类
// 接口定义
public interface IResultModel
{
bool IsSuccess { get; }
bool IsFailure { get; }
string Code { get; }
string Message { get; }
IEnumerable<ErrorInfo> Errors { get; }
}
public interface IResultModel<T> : IResultModel
{
T? Data { get; set; }
}
// 具体实现
public class ResultModel : IResultModel
{
public bool IsSuccess { get; set; }
public bool IsFailure { get; }
public string Code { get; set; }
public string Message { get; set; }
public IEnumerable<ErrorInfo> Errors { get; }
}
public class ResultModel<T> : IResultModel<T>
{
public bool IsSuccess { get; set; }
public bool IsFailure { get; }
public string Code { get; set; }
public string Message { get; set; }
public T? Data { get; set; }
public IEnumerable<ErrorInfo> Errors { get; }
}
[HttpGet]
public IResultModel<IEnumerable<WeatherForecast>> Get()
{
var result = Enumerable.Range(1, 3).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
return ResultModel<IEnumerable<WeatherForecast>>.Success(result, "查询成功");
}
返回结果:
{
"data": [
{
"date": "2024-01-01T12:00:00",
"temperatureC": 52,
"temperatureF": 125,
"summary": "Freezing"
}
],
"isSuccess": true,
"code": "200",
"message": "查询成功",
"errors": []
}
[HttpGet]
public IResultModel<IEnumerable<WeatherForecast>> Get()
{
return ResultModel<IEnumerable<WeatherForecast>>.Error("参数为空", "400");
}
返回结果:
{
"data": null,
"isSuccess": false,
"code": "400",
"message": "参数为空",
"errors": []
}
public IResultModel<bool> Save()
{
try
{
// 保存业务数据
return ResultModelFactory.Success(true, "保存成功");
}
catch (BaseException ex)
{
return ex.ToFailureResult<bool>();
}
catch (Exception ex)
{
return ex.ToFailureResult<bool>("保存失败");
}
}
ResultModel / ResultModel<T> 新增成功消息重载,支持业务消息保真ResultModelFactory,统一创建成功、失败和异常转换结果ResultModelExtensions,提供 DataOrEmpty、DataOrDefault 数据安全读取扩展ResultModelExceptionExtensions,支持 Exception.ToFailureResult<T>()MIT License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 is compatible. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 is compatible. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 is compatible. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 is compatible. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
| .NET Core | netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 netstandard2.1 is compatible. |
| MonoAndroid | monoandroid monoandroid was computed. |
| MonoMac | monomac monomac was computed. |
| MonoTouch | monotouch monotouch was computed. |
| Tizen | tizen60 tizen60 was computed. |
| Xamarin.iOS | xamarinios xamarinios was computed. |
| Xamarin.Mac | xamarinmac xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos xamarinwatchos was computed. |
Showing the top 5 NuGet packages that depend on Azrng.Core:
| Package | Downloads |
|---|---|
|
Common.EFCore
简单封装了一些EFCore常用方法 |
|
|
Azrng.Core.NewtonsoftJson
基本的NewtonsoftJson序列化类库封装 |
|
|
Azrng.Core.Json
基本的序列化类库封装 |
|
|
Azrng.ConsoleApp.DependencyInjection
基本的控制台依赖注入类库 |
|
|
Azrng.AspNetCore.Core
基本的公共类库 |
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.19.0 | 60 | 6/15/2026 |
| 1.18.0 | 105 | 6/2/2026 |
| 1.17.0 | 238 | 5/17/2026 |
| 1.16.0 | 163 | 3/26/2026 |
| 1.15.8 | 174 | 3/25/2026 |
| 1.15.7 | 184 | 3/19/2026 |
| 1.15.6 | 283 | 2/23/2026 |
| 1.15.5 | 233 | 2/11/2026 |
| 1.15.4 | 114 | 2/10/2026 |
| 1.15.3 | 116 | 2/10/2026 |
| 1.15.2 | 226 | 2/4/2026 |
| 1.15.1 | 129 | 1/31/2026 |
| 1.15.0 | 126 | 1/26/2026 |
| 1.14.0 | 116 | 1/20/2026 |
| 1.13.0 | 123 | 1/17/2026 |
| 1.12.0 | 131 | 1/8/2026 |
| 1.11.0 | 315 | 12/18/2025 |
| 1.10.0 | 313 | 12/16/2025 |
| 1.9.0 | 469 | 12/10/2025 |
| 1.8.4 | 997 | 11/6/2025 |