C#变量名"_"; (下划线) [英] C# Variable Name "_" (underscore) only

查看:1708
本文介绍了C#变量名"_"; (下划线)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在C#中遇到了一个小问题,那只是一个复制粘贴错误,但不知道C#如何接受它.

I was just hit with a minor issue in C#, it was just a copy-paste mistake but don't know how C# accept it.

此代码已成功编译...如何显示

This code gets compiled successfully...HOW

namespace DemoNS
{
    class DemoClass
    {
        String _ = new String('a', 1);        
    }
}

名为_的变量是否有任何默认含义?

Is there any default significance of variable named _?

推荐答案

如今,在C#7.0中,_有时确实具有重要意义.它成为新out var功能的丢弃运算符.当函数返回值并且您想通知编译器您将不使用它时可以使用它-这样就可以对其进行优化.或者在解构时(另一个C#7.0功能),您可以使用它来忽略不感兴趣的元组的一部分.

Nowadays with C# 7.0 the _ does have significance sometimes. It became the discard operator for the new out var feature. It is used when a function returns a value and you want to notify the compiler that you won't be using it - so it can be optimized out. Or when deconstructing (Another C# 7.0 feature) you can use it to ignore part of the tuple that you are not interested in.

示例 变种

void Test(out int i) => i = 1;

Test(out _); // _ was never declared, it will still compile in C# 7.0

var r = _;   // error CS0103: The name '_' does not exist in the current context

示例 解构元组

var Person = ("John", "Smith");

var (First, _) = Person; // '_' is not a declared

Debug.Print(First); // prints "John"
Debug.Print(_); // error CS0103: The name '_' does not exist in the current context

如果您确实声明了自己的名为_的变量,然后使用 discard运算符,则会出现问题,这会引起歧义.已在此处.

A problem arises if you do declare your own variable named _ and then use the discard operator it will cause ambiguity. This issue has been reported Here.

编辑 @ maf-soft在评论中指出,上述问题不是问题.如果声明了_,则将其像C#7.0之前的常规变量一样对待.

EDIT Above problem is not a problem as @maf-soft points out in comments. If _ was declared it is treated like a regular variable like it was pre C# 7.0.

这篇关于C#变量名"_"; (下划线)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆