Grace.Extensions 1.0.0.7

dotnet add package Grace.Extensions --version 1.0.0.7
                    
NuGet\Install-Package Grace.Extensions -Version 1.0.0.7
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Grace.Extensions" Version="1.0.0.7" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Grace.Extensions" Version="1.0.0.7" />
                    
Directory.Packages.props
<PackageReference Include="Grace.Extensions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Grace.Extensions --version 1.0.0.7
                    
#r "nuget: Grace.Extensions, 1.0.0.7"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Grace.Extensions@1.0.0.7
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Grace.Extensions&version=1.0.0.7
                    
Install as a Cake Addin
#tool nuget:?package=Grace.Extensions&version=1.0.0.7
                    
Install as a Cake Tool

Grace.Extensions

基于 ABP(Volo.Abp)的常用 .NET 拓展方法集合。

安装

dotnet add package Grace.Extensions

提供的扩展方法

String

// 空检查
"IsNotNullOrWhiteSpace".IsNullOrWhiteSpace(); // false
"IsNotNullOrWhiteSpace".IsNotNullOrWhiteSpace(); // true
"".IsNullOrEmpty(); // true

// 类型转换
"42".TryConvert(out int val); // true, val = 42
"{\"name\":\"test\"}".ToObject<MyDto>(); // 反序列化 JSON
"active".AsEnum<MyEnum>(); // 字符串解析为枚举
1.AsEnum<MyEnum>(); // int 解析为枚举

// 操作
"hello".Capitalize(); // "Hello"
"hello".Reverse(); // "olleh"
"abcdef".Substring(1, 3); // "bcd"
"too long text".Truncate(8, "..."); // "too..."
FormatWith("Hello {0}", "World"); // "Hello World"
"a,b,c".UnPackageToArray(); // ["a", "b", "c"]
"hello".FastHash(); // FNV-1a 32位哈希

// 脱敏
"13800138000".MaskLeft(4); // "********8000"
"13800138000".MaskRight(4); // "1380********"
"身份证号".MaskMiddle(2); // "身****号"

// 验证
"test@example.com".IsValidEmail(); // true
"13800138000".IsChinesePhone(); // true
"abc123".IsNumeric(); // false
"hello中world".ContainsChinese(); // true
"abc123".ExtractDigits(); // "123"

// HTML
"<p>text</p>".StripHtmlTags(); // "text"
"line1\nline2".ReplaceNewLinesToHtml(); // "line1<br />line2"

// 安全替换
"hello".SafeReplace("l", "x"); // "hexxo"

DateTime

DateTime.Now.ToUnixTimestampBySeconds(); // Unix 秒时间戳
DateTime.Now.ToUnixTimestampByMilliseconds(); // Unix 毫秒时间戳
1325376000L.ToLocalTimeDateBySeconds(); // Unix 秒时间戳 → 本地时间
DateTime.Now.DateFormatToWordString(); // "刚刚" / "3天前" / "1个月前" / "2025-01-01"
birthday.Age(); // 根据出生日期计算年龄

DateTime.Now.StartOfDay(); // 当天 00:00:00
DateTime.Now.EndOfDay(); // 当天 23:59:59.999
DateTime.Now.StartOfMonth(); // 当月 1 日 00:00:00
DateTime.Now.EndOfMonth(); // 当月最后一天 23:59:59.999

DateTime.Now.IsWeekend(); // 周六或周日
DateTime.Now.IsWeekday(); // 周一至周五
DateTime.Now.GetDateWithTime(10, 30, 0); // 替换时间部分为 10:30:00

Enum

public enum Status
{
    [Description("已激活")] Active,
    [Description("已禁用")] Disabled
}

Status.Active.GetDescription(); // "已激活"
EnumExtension.GetAllEnumItems<Status>(); // 获取所有有效枚举项
Status.Active.ToBizItem(); // new EnumBizItem(0, "已激活")

Guid

Guid.NewGuid().ToId(); // 无分隔符 32 位字符串

// 字符串 ↔ Guid
"xxxxxxxx".ToGuid(); // 字符串转 Guid
"xxxxxxxx".TryToGuid(); // 安全转换,失败返回 null
byteArray.ToGuid(); // byte[] 转 Guid

// 空检查
Guid.NewGuid().IsNullOrEmpty(); // false
Guid.Empty.IsNotNullOrEmpty(); // false
"xxxxxxxx".IsGuid(); // 是否为有效的 Guid 字符串

// 短编码(可 100% 还原,推荐用 10 位)
Guid.NewGuid().ToShortCode10(); // "0aB3cDeFgH"
GuidExtension.FromShortCode10("0aB3cDeFgH"); // 还原为原始 Guid
Guid.NewGuid().ToShortCode16(); // 16 位 base62 编码(可还原)
Guid.NewGuid().ToShortCode8(); // 8 位哈希(不可还原,仅唯一标识)

Enumerable

list.IsNullOrEmpty();
list.IsNotNullOrEmpty();
list.SelectAndDistinctList(x => x.Name); // Select + 去重 → List
list.SelectHash(x => x.Id); // Select → HashSet
list.DistinctBy(x => x.Category); // 按 key 去重
list.WhereIf(showInactive, x => !x.IsActive); // 条件过滤
list.Slice(100); // 分片
list.Slice(batch => Process(batch), batchSize: 300); // 分片处理
list.HasDuplicates(); // 重复检测
list.HasDuplicatesBy(x => x.Name); // 按 key 检测重复
list.AreSame(otherList); // 顺序比较
list.JoinToString(","); // 拼串
list.ForEach(item => Process(item));
set.AddRange(items); // HashSet 批量添加
query.PageByIndex(q => q.OrderBy(x => x.Id), 1, 20); // IQueryable 分页

Dictionary

dict.IsNullOrEmpty();
dict.GetValueOrDefault("key", defaultValue); // 安全取值
dict.GetValueOrInit("key", () => new Value()); // 惰性初始化
dict.GetValues(keys); // 批量获取
dict.Copy(source); // 批量复制
dict.AddOrUpdate("key", value);
dict.TryAdd("key", value);
dict.Remove(keyList); // 批量移除

Object

obj.ToSafeString(); // null → ""
obj.ConvertTo<int>(); // 通用类型转换(异常安全)
obj.ToJson(); // JSON 序列化(驼峰命名,忽略 null)
obj.ToDictionary(); // 反射转字典(属性名 → 值)

Integer

// 迭代
5.Times(i => Console.WriteLine(i));
0.Upto(5, i => Console.WriteLine(i)); // 0 → 4
0.UptoIncluding(5, i => Console.WriteLine(i)); // 0 → 5
5.Downto(0, i => Console.WriteLine(i)); // 5 → 1

// 数学
5.IsOdd(); // true
5.IsEven(); // false
2024.IsLeapYear(); // true

// 时间
7.DaysAgo(); // 7 天前
30.MinutesAgo(); // 30 分钟前
7.DaysFromNow(); // 7 天后

// TimeSpan
5.Days(); // TimeSpan.FromDays(5)
3.Hours();

// 进制
255.ToHex(); // "FF"
42.ToBinary(); // "101010"

// 存储单位
(1024L).KiloBytes(); // 1
(1048576L).MegaBytes(); // 1

Random

random.NextBool(); // 随机 true/false
random.NextBool(0.8); // 80% 概率 true
random.NextDigits(6); // "483921"(6 位随机数字)
random.NextString(8); // "aB3dEfGh"(8 位随机字母数字)

Span(零分配字符串分割)

foreach (var segment in "a,b,c".AsSpan().Split(','))
{
    // 零分配分割,适合高频解析场景
}

TypeParse(从 DataTable / 反射 / 配置安全取值)

obj.AsInt(); // → int
obj.AsBoolean(); // → bool
obj.AsGuid(); // → Guid
obj.AsDateTime(); // → DateTime
obj.AsString(); // 安全转字符串
obj.AsDecimal(); // → decimal
obj.AsNullable<int>(); // → int?(DBNull/null → null)

stream.ToByteArray(); // Stream → byte[]
stream.ReadString(); // Stream → string(UTF-8)
bytes.ToMemoryStream(); // byte[] → MemoryStream

Value

value.In(1, 2, 3); // 在列表中
value.NotIn(1, 2, 3); // 不在列表中
value.Between(1, 10); // 闭区间 [1, 10]
value.BetweenExclusive(1, 10); // 开区间 (1, 10)

使用方式

所有方法均为纯静态扩展,在引用命名空间后直接调用即可,无需额外配置:

using Grace.Extensions;

// JSON 序列化
var json = new User { Name = "Alice" }.ToJson();
var user = json.ToObject<User>();

// 字符串脱敏
"13800138000".MaskLeft(3); // "*********8000"
"13800138000".MaskRight(3); // "138********"

// 条件筛选
list.WhereIf(showActive, x => x.IsActive);

// 惰性初始化字典
dict.GetValueOrInit("key", () => LoadData());

// 集合分片处理
list.Slice(batch => SaveBatch(batch), batchSize: 1000);

依赖

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Grace.Extensions:

Package Downloads
Grace.Core

基于abp常用核心、工具类的模块封装

Grace.Cache

基于abp使用FreeRedis和资源池的缓存模块封装

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0.7 30 7/16/2026
1.0.0.6 54 7/16/2026
1.0.0.4 1,201 3/25/2026
1.0.0.3 337 3/11/2026
1.0.0.2 573 11/13/2025
1.0.0.1 284 6/4/2025