【发布时间】:2014-03-12 18:45:45
【问题描述】:
我一直在尝试简单的实验来学习 C# 方法。下面的代码简单地调用 playerSelection(),它向用户询问一个字符并将该字符返回给 Main(string[] args)。 Main 将其打印到控制台。使用下面的代码,我得到以下错误“非静态字段需要对象引用。”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SimpleFunction
{
class Program
{
static void Main(string[] args)
{
char cplayerChoice = playerSelection();
Console.WriteLine(cplayerChoice);
}
char playerSelection()
{
Console.WriteLine("\nEnter a Character");
char cplayerChoice = Console.ReadKey().KeyChar;
return cplayerChoice;
}
}
}
现在,如果我像这样添加静态一词:
static char playerSelection()
它可以编译和工作。我确实理解静态与非...抽象。
好的,这就是我感到困惑的地方,问题来了。
我正在从一本书中学习 C#,在那本书中,他们通过以下示例来说明使用方法:
using System;
namespace GetinPaid
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
}
void run()
{
double dailyRate = readDouble("Enter your daily rate:");
int noOfDays = readInt("Enter the number of days: ");
writeFee(calculateFee(dailyRate, noOfDays));
}
private void writeFee(double p)
{
Console.WriteLine("The consultant's fee is: {0}", p * 1.1);
}
private double calculateFee(double dailyRate, int noOfDays)
{
return dailyRate * noOfDays;
}
private int readInt(string p)
{
Console.Write(p);
string line = Console.ReadLine();
return int.Parse(line);
}
private double readDouble(string p)
{
Console.Write(p);
string line = Console.ReadLine();
return double.Parse(line);
}
}
}
问题:
为什么在他们的示例中他们可以不使用关键字 static 来调用方法,但我必须使用它?
谢谢!
【问题讨论】: