并非所有代码路径都返回值(C#)
我目前正在学习C#,而我在这个项目上遇到了麻烦。我正在学习方法和类,我正在制作一个测试程序,将两个数字相加,并在控制台中显示它们。我收到以下三个错误:并非所有代码路径都返回值(C#),c#,compiler-errors,C#,Compiler Errors,我目前正在学习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
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#知之甚少。有人能给我解释一下这些错误的含义,为什么会发生,以及如何修复它们吗?谢谢。修改您的
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=newaddnumbers()代码>仅当函数不是静态函数时
静态函数可以使用ClassName.functoname
调用,而非/静态(实例函数)则需要按照您描述的方式调用
addNumbers numbers = new addNumbers();
numbers.SomeFunction();
你可以这样看
Classname.SomeStaticVariable = 2;
如上所述,SomeStaticVariable
在任何时候对整个应用程序都是相同的。而下面描述的方法只有在内存中存在obj
时才可用
Classname obj = new ClassName();
obj.SomeVariable = 2;
将AddNumbers方法(inta,intb)设为静态,以便可以在main方法中使用它。
编辑地址编号(整数a、整数b):
public int addNumbers(int num1,int num2)
{
返回num1+num2;
}
之后,只需按以下方式使用该方法:
r=添加编号(a,b) 哇,我完全知道,但我从没想过。非常感谢!:)@FVNTUM,我修改了你的代码。检查我的答案。我已将addNumbers函数更改为静态函数,因此您可以在Main()范围内调用它代码>否-添加数字是一种方法。您不需要实例化只包含方法的类。