在 C# 7.0 支持使用下划线忽略不使用的变量
这个方法用的比较多的是在 out 参数,如使用 int 的尝试转换函数
var str = "123";
if (int.TryParse(str, out var _))
{
var n = _;
}
编译是不通过的,会出现 error CS0103: The name '_' does not exist in the current context
上面的代码还可以去掉 var 代码
var str = "123";
if (int.TryParse(str, out _))
{
//var n = _;
}
在 ValueTuple 也是很多的使用
var db = ("林德熙", "逗比");
var (lindexi, _) = db;
上面代码表示只拿出 lindexi 而 逗比是不拿出来的,虽然使用了下划线,但是如果在下面要使用下划线是无法编译通过
从这个特性可以推出在辣么大的使用,请看代码
Action<int> f = _ =>
{
var n = 2;
};
这样写表示不理会第一个参数,虽然这样写和下面代码是不等价的
Action<int> f = delegate
{
var n = 2;
};
但是从约定上,使用下划线表示忽略的代码
我搭建了自己的博客 https://lindexi.gitee.io/ 欢迎大家访问,里面有很多新的博客。只有在我看到博客写成熟之后才会放在csdn或博客园,但是一旦发布了就不再更新
如果在博客看到有任何不懂的,欢迎交流,我搭建了 dotnet 职业技术学院 欢迎大家加入
本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:http://blog.csdn.net/lindexi_gd ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系。