C#工具包 Newbe.Claptrap 0.2.10 发布,更花里胡哨

Newbe.Claptrap 0.2.10 发布,更花里胡哨。

更新内容

我们增加了简体中文的项目说明:

https://gitee.com/yks/Newbe.ObjectVisitor/blob/main/README_zh_Hans.md

现在,你可以通过上下文修改属性的值了:

//✔️ from 0.2
// 可以修改属性
o.V().ForEach((context) => ModifyData(context)).Run();

public static void ModifyData(IObjectVisitorContext<Yueluo,string> context)
{
    context.Value = context.Value.SubString(0,1);
}

现在,支持多次 ForEach 操作:

// ✔️ from 0.2
// 多重 foreach
o.V().ForEach((context)=>{}).ForEach((context)=>{}).Run();

现在,支持更多花里胡哨的属性条件判断:

//✔️ from 0.2
// 遍历指定类型的属性
o.V().ForEach<Yueluo, string>((context) => {});
// 和上一条完全一样
o.V().ForEach<Yueluo, string>((context) => {}, x => x.PropertyType == typeof(string));
// 遍历被标记了 RequiredAttribute 的 string 属性
o.V().ForEach<Yueluo, string>((context) => {}, x => x.PropertyType == typeof(string) && x.GetCustomAttribute<RequiredAttribute>());
// 遍历“是”或者实现了 IEnumerable<int> 接口的属性, 例如 List<int>, int[], IEnumerable<int>, HashSet<int> 等等。
o.V().ForEach<Yueluo, IEnumerable<int>>((context) => {}, x => x.IsOrImplOf<IEnumerable<int>>());
// 指定属性类型,并包含一个扩展的参数
o.V().WithExtendObject<Yueluo, StringBuilder>().ForEach<Yueluo, StringBuilder, string>((context) => {});

基准测试

我们更新了两个基准测试:

  1. FormatString 实现进行了优化,现在 Quick Style 和自己手写 ObjectVisitor 已经几乎没有区别。
  2. 使用 ObjectVisitor 来修改属性值的代价约为 1-5 微秒 (千分之一毫秒)。

详细的数据可以查看项目首页,此处仅给出图表说明。

FormatString

MOdifyData

文章

新增了一些相关的经验文章:

场景样例

我们增加了一些可以使用该库实现功能的场景和做法说明:

  • 将数据库链接字符串转型为数据模型,或者将数据模型格式化为链接字符串。
  • 将对象中满足手机号码格式的字段替换为密文,避免敏感信息输出。
  • 将实现了 IEnumerable<int> 的所有属性求和。

可以参阅《Newbe.ObjectVisitor 样例 1

简要说明

Newbe.ObjectVisitor 帮助开发者可以用最简单的最高效的方式访问一个普通 class 的所有属性。从而实现:验证、映射、收集等等操作。

例如, 在你的代码中有这样一个简单的类。

var order = new OrderInfo();

你想要将这个类所有的属性和值都打印出来,那么你可以采用反射来完成:

for(var pInfo in typeof(OrderInfo).GetProperties())
{
    Console.Writeline($"{pInfo.Name}: {pInfo.GetValue(order)}");
}

如果你使用这个类库,则可以采用以下方式来实现一样的效果:

// call .V what is a static extension method
// you get a visitor object for order
var visitor = order.V();

visitor.ForEach(context=>{
    var name = context.Name;
    var value = context.Value;
    Console.Writeline($"{name}: {value}");
}).Run();

// you can also make it into one line
order.V().ForEach(c=> Console.Writeline($"{c.Name}: {c.Value}")).Run();

// or using quick style
order.FormatToString();

那我为什么要这样做?

  • 因为这样更快!这个类库使用表达式树实现,因此它拥有比直接使用反射快上10倍的性能.
  • 因为这样更可读!通过这个类库你可以使用链式API和命名方法来创建一个委托,这样可以让你的代码实现和硬编码同样的可读效果。
  • 因为这样更具扩展性!如果使用了这个类库,你就拥有了一个简便的方法来访问一个类所有的属性。因此,你就做很多你想做的事情,比如:创建一个验证器来验证你的模型,修改一些可能包含敏感数据的属性从而避免输出到日志中,创建一个类似于AutoMapper的对象映射器但是拥有更好的性能,诸如此类。

GitHub 项目地址:https://github.com/newbe36524/Newbe.ObjectVisitor

Gitee 项目地址:https://gitee.com/yks/Newbe.ObjectVisitor

Newbe.ObjectVisitor

猜你喜欢

转载自www.oschina.net/news/119983/newbe-claptrap-0-2-10-released