【问题标题】:Not All Code Paths Return A Value (C#)并非所有代码路径都返回值 (C#)
【发布时间】:2016-09-03 16:10:19
【问题描述】:

我目前正在学习 C#,但我在使用这个程序时遇到了问题。我正在学习方法和类,我正在制作一个测试程序,将两个数字相加并在控制台中显示它们。我收到以下三个错误:

prog.cs(5,13): error CS0161: `Test.addNumbers(int, int)': not all code paths return a value
prog.cs(16,3): error CS0118: `Test.addNumbers(int, int)' is a `method' but a `type' was expected
prog.cs(17,7): error CS0841: A local variable `numbers' cannot be used before it is declared
Compilation failed: 3 error(s), 0 warnings

这是我的代码:

using System;

public class Test
{
    public int addNumbers(int num1, int num2) {
    int result;
    result = num1 + num2;
    }

    public static void Main()
    {
        int a = 2;
        int b = 2;
        int r;

        addNumbers numbers = new addNumbers();
        r = numbers.addNumbers(a, b);

        Console.WriteLine(r);
    }
}

我已经尝试了我所知道的一切,但正如我所说,我仍在学习,所以我对 C# 了解不多。谁能向我解释错误的含义,为什么会发生以及如何解决?谢谢。

【问题讨论】:

    标签: c# compiler-errors


    【解决方案1】:

    修改您的addNumbers 以返回一个值。函数签名声明它返回int,因此您必须从函数返回int

    using System;
    
    public class Test
    {
        public static int addNumbers(int num1, int num2) 
       {
        int result;
        result = num1 + num2;
        return result;
        }
    
        public static void Main()
        {
            int a = 2;
            int b = 2;
            int r;
    
    
            r = addNumbers(a, b);
    
            Console.WriteLine(r);
        }
    }
    

    编辑:

    仅当您的函数不是静态的时,您才需要addNumbers numbers = new addNumbers();

    可以使用ClassName.FunctonName 调用静态函数,而需要以您描述的方式调用非/静态(实例函数)。

    addNumbers numbers = new addNumbers();
    numbers.SomeFunction();
    

    您可以按照以下方式查看。

    Classname.SomeStaticVariable = 2;
    

    如上所述,SomeStaticVariable 在任何时候对于整个应用程序都是相同的。虽然下面描述的方式仅在内存中存在obj 时才可用。

    Classname obj = new ClassName();
    obj.SomeVariable = 2;
    

    【讨论】:

    • 哇,我完全知道这一点,但我从未想过。非常感谢! :)
    • @FVNTUM,我稍微修改了你的代码。检查我的答案。我已将您的 addNumbers 函数更改为静态,因此您可以在 Main() 范围内调用它。
    • 不需要addNumbers numbers = new addNumbers(); ??
    • 否 - addnumbers 是一种方法。您不实例化方法 - 只有类。
    【解决方案2】:

    将 AddNumbers(int a, int b) 方法设为静态,以便您可以在 main 方法中使用它。 编辑 AddNumbers(int a, int b): public int addNumbers(int num1, int num2) { return num1 + num2; }

    之后,只需以这种方式使用该方法: r = AddNumbers(a, b);

    【讨论】:

      猜你喜欢
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多