本文介绍了C#变量作用域和“开关"陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种代码通常可以在PHP中运行,但是由于C#的范围更为严格,因此并非如此.我无法找出一种方法来编写此代码,而无需重复自己的工作.

This kind of code would normally work in PHP, but since the scope is much more strict in C#, it's not. I can't figure out a way to write this code without repeating myself.

    static double Cube()
    {
        Console.Write("Enter the side length of the cube: ");
        try
        {
            double x = Convert.ToDouble(Console.Read());
            return Math.Pow(x, 3);
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid input, please enter a number.");
            Cube();
        }
        return 1;
    }

..稍后Main():

..Later in Main():

            switch (choice)
            {
                case 0:
                    return;
                case 1:
                    double final = Cube();
                    break;
                default:
                    Console.WriteLine("Please enter 0 or 1.");
                    Main();
                    break;
            }
            Console.WriteLine("The volume is: {0}", Convert.ToString(final));

Cube()方法可以正常工作,但是我认为这很混乱(最后, return 1 使编译器满意).但是出现一个错误,提示名称"final"在当前上下文中不存在.它找不到最终的.因此,让我看到这项工作的唯一方法是将 Console.WriteLine 语句放在double final = Cube()之后.

The Cube() method works fine, but it's messy in my opinion (return 1 at the end to make the compiler happy). But an error comes up saying The name 'final' does not exist in the current context. It can't find final. So the only way to make this work that I'm seeing is to put the Console.WriteLine statement right after the double final = Cube().

我也尝试过在开关外声明 double final; ,然后在每种情况下只设置 final ,但这也没有用.

I've also tried declaring double final; outside the switch, then just setting final inside each case, but that hasn't worked either.

谢谢!

推荐答案

如果要从 switch 范围之外访问 final ,则必须声明它也超出了这个范围.如果引用 final ,并且有一些代码路径不允许将值设置为 final ,则编译器将生气".

If you want to access final from outside the switch scope, you'll have to declare it outside that scope too. If you reference final and there are code paths that allow not setting a value to final, then the compiler will be "angry".

在php中,当您不为其分配任何内容时, final 神奇地为0.尝试在切换之前声明 final ,然后在每个 case 语句(包括 default case)中为其分配一个值.

In php, final would magically be 0 when you don't assign anything to it. Try declaring final before the switch, and then assign a value to it at each case statement including the default case.

这篇关于C#变量作用域和“开关"陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:23