全局变量和局部变量有问题 - c# [英] Having trouble with global variables and local variables - c#

查看:76
本文介绍了全局变量和局部变量有问题 - c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直试图让这个工作3天,我觉得我很接近它的工作!我已经尝试在控制台和Visual Studio的GUI中制作它,当我在GUI中创建时,我在visual studio中收到错误类名'?'不是这种语言的有效标识符。 - 我认为编译器出于某种原因出错了



当我把它作为控制台应用程序时,我得到了我的字符串数组错误(变量名)当前不存在上下文 - 我知道这意味着什么,但我已经使数组在全球范围内可用并且也使它成为它自己的类,如下所示:public static class Global

在控制台版本中我也得到:使用未分配的局部变量'desc1'我已经尝试将我的局部变量放在各个地方而不是adieu。



这是我的控制台代码,我正在尝试让它在那里工作,然后将其转换为GUI,所以我需要一些帮助我得到的GUI错误。 类名'?'不是这种语言的有效标识符。错误。我在MSDN上查找了它们,他们建议再次关闭并打开它(解决方案),这不起作用。



(控制台代码):

So I've been trying to get this to work for 3 days and I'm close to it working, I think! I have tried making it in the console and in GUI of Visual Studio, when I make it in the GUI I am getting a error in visual studio "The class name '?' is not a valid identifier for this language." - I think the compiler is erroring for some reason

When I make it as a console application I get my string array erroring " (Variable name) Does not exist in current context" - I know what this means but I have made the array available globally and also made it it's own class, like so: "public static class Global"
In the console version I also get: "Use of unassigned local variable 'desc1'" I have tried putting my local variables in various places to no adieu.

Here is my console code, I'm trying to get it to work there then convert it to a GUI so I need some help with the GUI error I'm getting. The ""The class name '?' is not a valid identifier for this language." error. I looked it up on the MSDN and they recommended closing and opening it (solution) again which didn't work.

(Console code):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AnotherFlexibleOrder
{
    public static class Global
    {
         public static int[] itemNumber = { 112, 123, 134, 213, 224, 235 };
         public static string[] description = { plate, cup, bowl, vase, planter, statue };
         public static double[] price = { 16.95, 10.95, 14.25, 21.95, 45.99, 89.99 };
         public static bool isValidOption = false;
    }
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            Console.WriteLine("Please enter an item number or description.");
            string item = Console.ReadLine();
            if (int.TryParse(item, out number))
            {
                GetDetails(number);
            }
            else
            {
                GetDetails(item);
            }
        }
        private static void GetDetails(int num)
        {
            string desc1;
            double price1;
            for (int x = 0; x < Global.itemNumber.Length; ++x)
            {

                if (num == Global.itemNumber[x])
                {
                    Global.isValidOption = true;
                    desc1 = Global.description[x];
                    price1 = Global.price[x];
                }
                if (Global.isValidOption)
                {
                    Console.WriteLine("You selected item # {0} which is {1} and costs {2}.", num, desc1, price1);

                }
                else
                {
                    Console.WriteLine("Invalid item #.");
                }
            }
        }
        private static void GetDetails(string word)
        {
            string desc1;
            int item1;
            double price1;
            for (int x = 0; x < Global.description.Length; ++x)

            {

                if (word == Global.description[x])
                {
                    Global.isValidOption = true;
                    desc1 = Global.description[x];
                    price1 = Global.price[x];
                    item1 = Global.itemNumber[x];
                }
                if (Global.isValidOption)
                {
                    Console.WriteLine("You selected {0} which is item # {1} and costs {2}.", desc1, item1, price1);
                }
                else
                {
                    Console.WriteLine("Invalid item1 #!");
                }
            }
        }
    }
}





这是全局类中的字符串给出了当前上下文中不存在错误:当前上下文中不存在名称'盘'



然后我在GetDetails()方法中的局部变量给我这个错误:使用未分配的局部变量'price1'



这是我的作业,我们有重载GetDetails方法。我能够让代码工作得更多或更少,但我无法弄清楚这些错误,我发誓我做的一切都是正确的。



我缺少什么?我已经尝试将变量放在几个地方,并且我尽我所能调试。可能还有其他逻辑错误,但我无法进行编译以进一步调试。



我尝试了什么:



我已经尝试将变量和数组放在不同的位置,以使它们成为全局或本地的。



当我得到类名'时,尝试在visual studio中重启解决方案?'不是这种语言的有效标识符。



It's that string in the global class that is giving me the "does not exist in current context" errors: "The name 'plate' does not exist in the current context"

Then my local variables in the GetDetails() methods are giving me this error: "Use of unassigned local variable 'price1'"

This is for my homework, we have to overload the GetDetails method. I was able to get the code working more or less but I just can't figure these errors out I swear I did everything right.

What am I missing? I have tried putting the variables in several places and I debugged to the best of my abilities. There might be other logical errors but I can't get it to compile to debug any further.

What I have tried:

I have tried putting the variables and arrays in different places to get them to be global or local.

Tried restarting solution in visual studio when I get "The class name '?' is not a valid identifier for this language."

推荐答案

字符串文字需要用引号括起来 - plate,而不是 plate



变量需要明确分配才能使用。编译器不够聪明,以至于在 isValidOption 设置为 true 。在以前的 if 块中写入成功消息会更容易。



你继续即使您找到了有效的项目,也会遍历项目。一旦找到该项目,你应该中断



你正在写无效项目消息太快 - 例如,如果用户输入杯子会怎样?



isValidOption 应该是 GetDetails 方法中的局部变量。您只需要知道在循环结束后是否写入无效项消息。



伪代码:

String literals need to be enclosed in quotes - "plate", not plate.

Variables need to be definitely assigned before they can be used. The compiler isn't smart enough to work out that the price and description will always be assigned by the time that isValidOption is set to true. It would be easier to write the success message inside the previous if block instead.

You're continuing to loop over the items even after you've found a valid item. You should break out of the loop as soon as the item is found.

You're writing the Invalid item message too soon - what happens if the user enters "cup", for example?

isValidOption should really be a local variable within the GetDetails methods. You only need it to know whether or not to write the Invalid item message after the loop has finished.

Pseudo-code:
bool isValidItem = false;

For each index in the range:
{
    If the item at this index matches the entered item:
    {
        Write the "found it" message
        Set isValidItem to true
        Break out of the for loop
    }
}

If isValidItem is false:
{
    Write the "invalid item" message
}


Ok * facepalm *我应该知道字符串数组中的引号。非常感谢你的回复!



所以我尝试了你对我的方法所说的话,它给了我一个不能在这个范围内声明,因为它会给'isValidItem'赋予不同的含义错误。当我把它保存为isValidOption = true时,错误就消失了;但我不认为isValidOption变量被改为true,因为我的输出出错了。当我回去并将代码行更改为bool isValidItem = true;时(试图将其改为true)它会吐出不同的意义错误。



这是我当前的代码,就像我说的我不知道如何将布尔变量更改为true,或者为什么这不起作用。 />


Ok *facepalm* I should have known that about the quotes in the string array. Thank you so much for the reply!

So I tried what you said about my method and it was giving me a "cannot be declared in this scope because it would give a different meaning to 'isValidItem'" error. The error went away when I kept it as isValidOption = true; but I don't think the isValidOption variable was getting changed to true because my output came out wrong. When I went back and changed the line of code to "bool isValidItem = true;" (trying to change it to true) it would spit out that different meaning error.

This is my current code, Like I said I'm not sure how else to change the boolean variable to true, or why this isn't working.

private static void GetDetails(string word)
        {
            bool isValidOption = false;
            string desc1;
            int item1;
            double price1;
            for (int x = 0; x < Global.description.Length; ++x)

            {

                if (word == Global.description[x])
                {

                    desc1 = Global.description[x];
                    price1 = Global.price[x];
                    item1 = Global.itemNumber[x];
                    bool isValidOption = true;
                    Console.WriteLine("You selected {0} which is item # {1} and costs {2}.", desc1, item1, price1);
                    break;
                }
            }
                    if (isValidOption == false)
                    {
                        Console.WriteLine("Invalid item # String");

                    }
        }





这是我所在的2个实例中的当前错误试图将isValidOption更改为true并且它不起作用:



错误1无法在此范围内声明名为'isValidOption'的局部变量,因为它会给出不同的意思是'isValidOption',它已经在'父或当前'范围内用于表示别的东西



也许我无法改变它因为它在里面for和if语句?我尝试将公共放在布尔声明的前面。



就像我说我的输出错了。



(错误的输出我的意思是无效的项目#总是显示,有时多次显示)



再次感谢!



This is the current error from the 2 instances where I'm trying to change the isValidOption to true and it's not working:

"Error 1 A local variable named 'isValidOption' cannot be declared in this scope because it would give a different meaning to 'isValidOption', which is already used in a 'parent or current' scope to denote something else"

Maybe I can't change it because it's inside a for and an if statement? I tried putting "public" in front of the boolean declaration too though.

Like I said my output was wrong.

(By wrong output I mean the invalid item # was always showing and sometimes multiple times)

Thanks again!


这篇关于全局变量和局部变量有问题 - c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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