C# 10 新特性 —— CallerArgumentExpression

C# 10 新特性 —— CallerArgumentExpression

Intro

C# 10 支持使用 CallerArgumentExpression 来自动地获取调用方的信息,这可以简化我们现在的一些代码,让代码更加简洁,一起看下面的示例吧

Caller Info

C# 在 5.0 的时候开始支持 Caller Info 自动获取调用方的一些信息,C# 5 开始支持的 Caller Info Attribute 有三个,

  • [CallerMemberName] - 调用方成员名称,方法名或者属性名.

  • [CallerFilePath] - 调用方源代码所在文件路径

  • [CallerLineNumber] - 调用方所在源代码的行数信息

在方法参数中添加一个 Attribute 来获取调用方信息,使用示例如下:

public static void MainTest()
{// 我是谁,我在哪儿DumpCallerInfo();
}private static void DumpCallerInfo([CallerFilePath] string? callerFilePath = null,[CallerLineNumber] int? callerLineNumber = null,[CallerMemberName] string? callerMemberName = null
)
{Console.WriteLine("Caller info:");Console.WriteLine($@"CallerFilePath: {callerFilePath}
CallerLineNumber: {callerLineNumber}
CallerMemberName: {callerMemberName}
");
}

针对 CallerLineNumber 的类型是 int,所以参数类型需要能够直接接收 int,如上面的 [CallerLineNumber] int? callerLineNumber = null 也可以改成 [CallerLineNumber] int callerLineNumber = -1 或者 [CallerLineNumber] long callerLineNumber = -1

但是不能改成 [CallerLineNumber] string callerLineNumber = null 或者 [CallerLineNumber] short callerLineNumber = -1

string 类型不兼容,short 不能隐式转换

上面代码输出结果类似下面:

Caller info:
CallerFilePath: C:\projects\sources\SamplesInPractice\CSharp10Sample\CallerInfo.cs
CallerLineNumber: 8
CallerMemberName: MainTest

66d0b12d355ee08fef94bbd28b309ca2.png

CallerArgumentExpression

CallerArgumentExpression 也是属于一种 Caller Info

下面这里是利用 CallerArgumentExpression 实现的几个验证方法,如果参数不合法就抛出一个异常,通过 CallerArgumenExpression 来自动的获取调用方的参数表达式

public static class Verify
{public static void Argument(bool condition, string message, [CallerArgumentExpression("condition")] string? conditionExpression = null){if (!condition) throw new ArgumentException(message: message, paramName: conditionExpression);}public static void NotNullOrEmpty(string argument, [CallerArgumentExpression("argument")] string? argumentExpression = null){if (string.IsNullOrEmpty(argument)){throw new ArgumentException("Can not be null or empty", argumentExpression);}}public static void InRange(int argument, int low, int high,[CallerArgumentExpression("argument")] string? argumentExpression = null,[CallerArgumentExpression("low")] string? lowExpression = null,[CallerArgumentExpression("high")] string? highExpression = null){if (argument < low){throw new ArgumentOutOfRangeException(paramName: argumentExpression,message: $"{argumentExpression} ({argument}) cannot be less than {lowExpression} ({low}).");}if (argument > high){throw new ArgumentOutOfRangeException(paramName: argumentExpression,message: $"{argumentExpression} ({argument}) cannot be greater than {highExpression} ({high}).");}}public static void NotNull<T>(T? argument, [CallerArgumentExpression("argument")] string? argumentExpression = null)where T : class{ArgumentNullException.ThrowIfNull(argument, argumentExpression);}
}

来看一个使用调用示例:

var name = string.Empty;
InvokeHelper.TryInvoke(() => Verify.NotNullOrEmpty(name));

上面的 InvokeHelper.TryInvoke 是封装的一个方法,如果有异常会记录一个日志

上面代码执行结果如下:

894cdf74ba15e51ba61739b620173ba6.png

可以看到我们的名称也是被记录了下来 Parameter 名字就是我们传入的变量名,不需要我们再手动的额外加一个 nameof(name)

再来看一个调用示例,调用代码如下:

var num = 10;
InvokeHelper.TryInvoke(() => Verify.InRange(num, 2, 5));
InvokeHelper.TryInvoke(() => Verify.InRange(num, 10 + 2, 10 + 5));

输出结果如下:

ba4e3d4f070ad291b61657a90617f95b.png

如果没有变量名或者属性名等,就会直接用传入进来的 value 字面量,如果传入进来的是一个表达式,那么记录下来的就是表达式本身,比如上面输出的 5/10 + 2,而 num 是传入的一个变量,就会获取到变量的名字,是不是很神奇,很多验证的地方就可以简化很多了

Sample

CallerArgumentExpression 有一个很典型的一个实际应用就是 .NET 6 里新增的一个 API

ArgumentNullException.ThrowIfNull() 方法,这个方法的实现如下:

/// <summary>Throws an <see cref="ArgumentNullException"/> if <paramref name="argument"/> is null.</summary>
/// <param name="argument">The reference type argument to validate as non-null.</param>
/// <param name="paramName">The name of the parameter with which <paramref name="argument"/> corresponds.</param>
public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
{if (argument is null){Throw(paramName);}
}[DoesNotReturn]
private static void Throw(string? paramName) =>throw new ArgumentNullException(paramName);

源码可以从 Github 上看 https://github.com/dotnet/runtime/blob/v6.0.0/src/libraries/System.Private.CoreLib/src/System/ArgumentNullException.cs

我们实际调用的时候就可以不传参数名,会自动的获取参数名,示例如下:

object? xiaoMing = null;
InvokeHelper.TryInvoke(() => ArgumentNullException.ThrowIfNull(xiaoMing));

输出结果如下:

dd9b6832eb081fbc35a2f5b53dbf37c7.png

从上面的结果我们可以看到,参数名已经自动的解析出来了

More

升级 .NET 6 的小伙伴快用这个改造你的代码吧,然后就是很多 null 检查也可以使用新的 ArgumentNullException.ThrowIfNull 去简化代码吧~~

想使用上述代码测试,可以从 Github 获取 https://github.com/WeihanLi/SamplesInPractice/blob/master/CSharp10Sample/CallerInfo.cs

References

  • https://www.codeproject.com/Tips/606379/Caller-Info-Attributes-in-Csharp-5-0

  • https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/caller-argument-expression?WT.mc_id=DT-MVP-5004222

  • https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/caller-information?WT.mc_id=DT-MVP-5004222

  • https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10?WT.mc_id=DT-MVP-5004222#callerargumentexpression-attribute-diagnostics

  • https://github.com/dotnet/runtime/blob/v6.0.0/src/libraries/System.Private.CoreLib/src/System/ArgumentNullException.cs

  • https://github.com/WeihanLi/SamplesInPractice/blob/master/CSharp10Sample/CallerInfo.cs

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/295298.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一款不错的编程字体Source Code Pro

我以前一直是用的MS自家的是Consolas的字体&#xff0c;这个字体基本上具有编程字体所需的所有要素&#xff1a;等宽、支持ClearType、中文字体大小合适&#xff0c;l和1&#xff0c;o和0很容易区分。非要挑刺的话就是字体比较小&#xff0c;9号和10号字区别不大&#xff0c;长…

Android之failed for task ‘:app:dexDebug‘致gradle编译OOM问题解决(android-support-multidex)

当我们的业务越来越多,项目里面的方法和第三方的jar包也会越来越多,然后昨晚就遇到了下面这个问题 UNEXPECTED TOP-LEVEL EXCEPTION:at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.j…

当代年轻人熬夜晚睡的原因找到了!

全世界只有3.14 % 的人关注了爆炸吧知识有人熬夜为了离梦想更近有人熬夜为了给自家爱豆做数据有人熬夜只是因为深夜才有点自己的时间还有人是因为“沉迷”这些优质视频号忘记要睡在过去一段时间里&#xff0c;视频号可能是微信迭代最多&#xff0c;变化最多&#xff0c;也受到最…

怎么安装SharePoint2013 preview 在SQL2012 和 Windows Server 2008 R2 SP1

微软上周发布了其支柱产品Office2013 和SharePoint2013 preview. 对于以SharePoint 吃饭的人当然是很兴奋。今天我在这里演示一下怎么安装SharePoint2013 preview 在SQL2012 和 Windows Server 2008 R2 SP1 。 1.需要在你的Active Directory&#xff08;AD)里建一个用户 ,我把它…

c++ 与 java_Java与C++比较

本文仅从片面的角度比较Java与C的一些特性&#xff0c;如有错误的地方&#xff0c;请指正。语言特性上的一些差异&#xff1a;1、Java没有无符号整数&#xff0c;C/C#都有。2、Java中不存在指针。Java的引用是功能弱化的指针&#xff0c;只能做“调用所指对象的方法”的操作&am…

Mac 登陆 去掉 其他用户

2019独角兽企业重金招聘Python工程师标准>>> 打开 终端 sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED -bool FALSE 转载于:https://my.oschina.net/liuchuanfeng/blog/617387

使用 Windbg 分析一个 异步操作 引发的 Crash 异常

上周我们收到了一个客户的紧急求助&#xff0c;他们的一个 iis应用程序池 经历了频繁重启&#xff0c;即使从错误日志中也不得到任何有用的信息&#xff0c;异常信息如下&#xff1a;System.NullReferenceException : Object reference not set to an instance of an object. S…

wxGlade的图标,原来是来自蒙德里安的名画!

一直用wxGlade做GUI的&#xff0c;今天突然发现它的图标和一副油画很像。 wxGlade的图标&#xff0c;图标的文件名竟然就叫做mondrian.ico 蒙德里安创造了很多这种纯粹的基本要素的作品&#xff0c;下面是其中之一&#xff0c;《构图》&#xff08;Composition 1929 - Piet Mon…

SAP HANA解读-2012 SAP商业同略会分享

7月26日和27日&#xff0c;我受邀参加了SAP在国家会议中心举办的“蕴韬略促转变共发展”为主题的中国商业同略会&#xff0c;下面就参会的一些感想和大家分享一下。 SAP中国商业同略会是第二次在北京举办&#xff0c;此次大会汇聚国内外知名商业领袖、企业高层、行业权威、专家…

java日期加减秒_Java日期——年、月、日、时、分、秒、周加减计算

Java日期——年、月、日、时、分、秒、周加减计算Java日期——年、月、日、时、分、秒、周加减计算1.Pom依赖joda-timejoda-time2.9.92.示例代码package com.example.demo.controller;import org.joda.time.DateTime;import java.text.SimpleDateFormat;import java.util.Date;…

遍历Map的四种方法

map遍历经常忘记&#xff0c;老是在网上找&#xff0c;干脆自己记录下来 public static void main(String[] args) {Map<String, String> map new HashMap<String, String>();map.put("1", "value1");map.put("2", "value2&qu…

不可思议!这篇全篇脏话的文章竟然发表了

全世界只有3.14 % 的人关注了爆炸吧知识一教授为了抗议三流科学杂志发送垃圾邮件&#xff0c;回复了一篇全文只重复七个脏话字眼的论文&#xff0c;竟被出版&#xff01;这是十几年前&#xff0c;麻省理工大学的一个教授埃迪科勒&#xff0c;发表的一篇名为 Get me off Your Fu…

设置圆角、定向设置圆角-按钮等控件

为什么80%的码农都做不了架构师&#xff1f;>>> //定向设置圆角UIBezierPath *maskPath [UIBezierPath bezierPathWithRoundedRect:whiteView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];CASha…

C# 10 新特性 —— Lambda 优化

C# 10 新特性 —— Lambda 优化IntroC# 10 对于 Lambda 做了很多的优化&#xff0c;我们可以在 C# 中更加方便地使用委托和 Lambda 了&#xff0c;下面就来看一些示例Lambda EnhancementsNatural types for lambdasC# 10 可以更好做类型推断&#xff0c;很多时候编译器可以自动…

40个最好的Tumblr主题

如果安装了一款较好的Tumblr主题&#xff0c;你的Tumblr空间将焕然一新。然而找到一款合适的主题并不是一件容易的事&#xff0c;这正是本文中我整理那么多优质的Tumblr模板作为灵感的原因。其中有一些免费的Tumblr主题&#xff0c;另外的一些付费的Tumblr主题也确实很棒&#…

以太网

以太网将数据链路层的功能划分到了两个不同的子层&#xff1a; 1) 逻辑链路控制 (LLC) 子层 2) 介质访问控制 (MAC) 子层。 逻辑链路控制 (LLC) 子层&#xff1a; 以太网&#xff0c;IEEE 802.2 标准规范 LLC 子层的功能&#xff0c;而 802.3 标准规范 MAC 子层…

Android之Universal-Image-loader

一、介绍 Android-Universal-Image-Loader是一个开源的UI组件程序&#xff0c;该项目的目的是提供一个可重复使用的仪器为异步图像加载&#xff0c;缓存和显示。所以&#xff0c;如果你的程序里需要这个功能的话&#xff0c;那么不妨试试它。因为已经封装好了一些类和方法。我们…

java 有没有with语句_Java中的try-with-resources语句

在这个Java程序示例中&#xff1a;package test;import java.sql.DriverManager;import java.sql.Connection;import java.sql.Statement;public class Test{private static void example(){String url "jdbc:oracle:thin://localhost:7856/xe";String user "…

现代女性都有哪些烦恼?

1 医生&#xff0c;咱可以先拔下来么&#xff01;▼2 靓仔&#xff0c;我笑得停不下来&#xff01;&#xff08;via.豆瓣哈组&#xff09;▼3 边做饭边把锅给洗了&#xff08;素材来源网络&#xff0c;侵删&#xff09;▼4 令人无路可退的辞职方式&#xff01;&#xff1f;&…

c++11新特性(4) lambda捕捉块

lambda表达式中的方括号成为捕捉块,能够在这里指定怎样从所在的作用域中捕捉变量. 捕捉的意思是指能够在该lambda中使用该变量.即能够捕获外部变量在lambda表达式内使用. 能够使用两种方式来捕捉所在的作用域中的全部变量. []:通过值捕捉全部变量 [&]:通过引用捕捉全部变量…