【发布时间】:2019-05-31 15:49:41
【问题描述】:
我创建了另一个类(计算)并在其中创建了一个函数来检查数字是偶数还是奇数。我想在我的程序类中调用这个函数,这样它就可以检查变量(结果)是偶数还是奇数。
我尝试调用类似的方法:CheckEvenOrOdd(result)。
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 = number2 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
// i tried this here but it doesn't work: CheckEvenOrOdd(result)
}
}
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 ");
}
}
}
【问题讨论】:
-
天啊。我们从哪里开始。您不能简单地通过调用它的名称来访问另一个类的方法。但是,由于它是静态的,因此使用
Calculations.CheckEvenOrOdd(someNumber)应该可以工作 -
@AviMeltser 在最近的 C# 版本中,使用适当的
using语句,您可以(如果是static)。 -
@AviMeltser 谢谢。如果它不是静态的,我该怎么做?
-
@AntonioBuzbuchi 没问题。它不是静态的,您需要创建您尝试调用其方法的类的实例。推荐阅读面向对象编程docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…