我创建了另一个类(计算),并在其中创建了一个函数来检查数字是偶数还是奇数。我想在程序类中调用此函数,以便它可以检查变量(结果)是偶数还是奇数。
我试图调用如下方法:CheckEvenOrOdd(result)。
function func(){
var x; //x is declared and its value is undefined
console.log(x)
x = 2;
console.log(x)
}
func()
答案 0 :(得分:1)
由于您的方法位于不同的类中,因此必须将其设置为静态,然后先按类名然后按方法名进行调用。如果不是静态的,则必须先实例化该类的新实例,然后才能访问其任何方法。
(顺便说一句,您要将number2乘以number2,并在下面的代码中为您更改了它)
静态:
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number1 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
Calculations.CheckEvenOrOdd(result);
Console.ReadLine();
}
}
public static class Calculations
{
public static void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}
不是静态的:
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number1 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
Calculations calc = new Calculations();
calc.CheckEvenOrOdd(result);
Console.ReadLine();
}
}
public class Calculations
{
public void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}