简体   繁体   English

'变量已赋值,但从未使用过它的值' & '该名称在当前上下文中不存在'

[英]'The variable is assigned but its value is never used' & 'The name does not exist in the current context'

I've looked into this but still can't seem to figure it out.我已经调查过了,但似乎仍然无法弄清楚。

I thought I've used the variable, but I'm guessing I haven't.我以为我已经使用了变量,但我猜我没有。 I'm very new to C#, coming over from Python, so it could be a language/formatting difference I haven't ironed out yet?我对 C# 很陌生,从 Python 过来,所以这可能是我还没有解决的语言/格式差异?

I'm getting "The name 'number' does not exist in the current context" and "The variable 'number_wording' is assigned but its value is never used"我收到“当前上下文中不存在名称‘number’”和“变量‘number_wording’已分配,但它的值从未使用过”

using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
    number = 1;

    if (number == 1)
    {
        string number_wording = "the number is 1";
    }
    else
    {
        string number_wording = "the number is not 1";
    }
    Console.WriteLine("{0}", number_wording);

You must declare every variable that you use in C# and you must declare it in a scope that can be seen by everything that uses it:您必须声明在 C# 中使用的每个变量,并且必须在 scope 中声明它,所有使用它的人都可以看到:

int number = 1;

string number_wording = "the number is not 1";

if (number == 1)
{
    number_wording = "the number is 1";
}

Console.WriteLine("{0}", number_wording);

Perhaps this is slightly nicer:也许这稍微好一点:

int number = 1;

Console.WriteLine("the number is {0}", number == 1 ? "1" : "not 1");

Or even this:甚至这样:

int number = 1;
string number_wording = $"the number is {(number == 1 ? "1" : "not 1")}";
Console.WriteLine(number_wording);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM