C# 变量名“_”仅(下划线)

发布于 2024-11-15 00:27:59 字数 236 浏览 3 评论 0原文

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

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

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

名为 _ 的变量有默认含义吗?

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 _?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

萌能量女王 2024-11-22 00:27:59

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

示例
out var

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

如果您确实声明了自己的名为 _ 的变量,然后使用丢弃运算符,则会出现问题,这会导致歧义。此问题已在此处报告。

编辑
正如@maf-soft 在评论中指出的那样,上述问题不是问题。如果声明了 _,它将被视为常规变量,就像 C# 7.0 之前的版本一样。

EDIT 2021 有点迟了

在 c# 8.0 中 _ 也成为 switch 表达式中的 catch all 运算符,正式命名为 丢弃运算符

示例丢弃运算符

var moreThan20 = val switch
{
    >20 => "Yes",
    >50 => "Yes - way more!",
    _ => "No",
};

丢弃运算符在没有其他模式匹配时分配一个值

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.

Example
out var

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

Example
deconstructing a Tuple

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

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.

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.

EDIT 2021 A little overdue

In c# 8.0 _ also became the catch all operator in a switch expression, officially named the discard operator

Example discard operator

var moreThan20 = val switch
{
    >20 => "Yes",
    >50 => "Yes - way more!",
    _ => "No",
};

The discard operator assigns a value when no other pattern matches

素染倾城色 2024-11-22 00:27:59

不,没有默认意义,_ 只是一个与其他变量名称一样的变量名称。

我喜欢以与 Prolog 的匿名变量类似的方式使用它:当您创建一个忽略其中一个参数的 lambda 时,您可以将其命名为 _

EventHandler handler = (_, e) => Console.WriteLine(e);

另一方面,我不会使用如果在其他地方,您应该使用描述性名称。

编辑:请注意,在 C# 7.0 中,_ 有时具有特殊含义。例如,即使您没有声明名为 _ 的变量,您也可以编写 _ = new String('a', 1);

No, there is no default significance, _ is just a variable name like any other.

I like to use it in similar way to Prolog's anonymous variables: when you're creating a lambda that ignores one of its parameters, you can name it _:

EventHandler handler = (_, e) => Console.WriteLine(e);

On the other hand, I wouldn't use it anywhere else, you should use a descriptive name instead.

EDIT: Note that in C# 7.0, _ sometimes has special meaning. For example, you can write _ = new String('a', 1);, even if you didn't declare a variable named _.

庆幸我还是我 2024-11-22 00:27:59

前面的答案都很有用,但我认为他们错过了一个用例。
如果您不想使用函数的返回值,您可以使用 _ 字符,即:

而不是

int returnvalue = RandomFunction();

您可以这样做

_ = RandomFunction();

The previous answers were all useful, but I think they missed a use case.
If you don't want to work with a function's return value, you can use the _ character, i.e.:

instead of

int returnvalue = RandomFunction();

you can do

_ = RandomFunction();
埋情葬爱 2024-11-22 00:27:59

_ 是与 ai 相同的有效字符,并且在语法上变量可以以 _ 开头,因此单个字符_ 的名称在语法上完全正确。这不是一个很好的选择,但可以编译并正常工作。

_ is a valid character the same as a or i and syntactically variables can start with _ so a single character name of _ is perfectly syntactically correct. Not a really good choice but will compile and work fine.

无人问我粥可暖 2024-11-22 00:27:59

它是一个丢弃变量,它是一个占位符变量并且未使用。它告诉编译器对输出值不感兴趣。
示例:创建一个文件处理类。构造函数将启动该过程。并且,我们有复制、删除操作。假设,一个特定的类有责任启动该进程,但无需担心其他操作。然后我将声明像 _ = new FileListener(); 我不会担心输出。
其他类可以实例化 FileListener obj = new FileListener(); 或可以调用其他操作作为 FileListener.CopyFile()

示例:

    class Program
        {
            static void Main(string[] args)
            {
   /// Ignore the instance value but initialized the operation by instantiation
                _ = new FileListener();
                
                Console.WriteLine("Hello World!");
            }
        }
        
        public class FileListener 
        {
            public FileListener()
            {
                /// Logic to listen external file changes
            }
            public static void DeleteFile()
            { }
            public static void CopyFile()
            { }
        }

Its a discards, which is a placeholder variable and unused. It tells compiler that not interested in output value.
Example: Created a File handing class. Constructor will initiate the process. And, we have Copy, Delete operation. Suppose, one particular class has the responsibility to initiate the process but no need to worry about other operations. Then I will declare like _ = new FileListener(); I will not worry about output.
Other class can have instantiate FileListener obj = new FileListener(); or can call other operation as FileListener.CopyFile()

Sample:

    class Program
        {
            static void Main(string[] args)
            {
   /// Ignore the instance value but initialized the operation by instantiation
                _ = new FileListener();
                
                Console.WriteLine("Hello World!");
            }
        }
        
        public class FileListener 
        {
            public FileListener()
            {
                /// Logic to listen external file changes
            }
            public static void DeleteFile()
            { }
            public static void CopyFile()
            { }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文