2018-10-31-C#-7.0-使用下划线忽略使用的变量

title author date CreateTime categories
C# 7.0 使用下划线忽略使用的变量
lindexi
2018-10-31 14:4:9 +0800
2018-10-22 15:1:26 +0800
C#

在 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;
            };

但是从约定上,使用下划线表示忽略的代码

posted @ 2019-11-21 16:05  lindexi  阅读(101)  评论(0编辑  收藏  举报