static method and non-static menthod
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cash
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
// writeFee(calculate(dailyRate, workDay));
// 对于非 static 方法,若想像上面这样直接调用则会报以下错
// Error 1 An object reference is required
// for the non-static field, method, or
// property 'Cash.Program.readDouble(string)'
printfOtherthing("static method is called."); // static 方法可直接调用
Program program = new Program(); // 非 static 方法需要先创建一个对象
// 然后用对象调用
program.printSomething("non-static menthod is called.");
}
public void run()
{
double dailyRate = readDouble("please enter your rate: ");
int workDay = readInt("please enter your days of working: ");
writeFee(calculate(dailyRate, workDay));
}
private void writeFee(double p)
{
Console.WriteLine("The consultant's fee is: {0}", p * 1.6);
}
private double calculate(double dailyRate, int workDay)
{
return dailyRate * workDay;
}
private int readInt(string p)
{
Console.WriteLine(p);
string a = Console.ReadLine(); // 读取输入的字符(readline读取的
// 字符都是 string 类型)
return int.Parse(a); // 把 a 转换为 int 类型,并返回
}
private double readDouble(string p)
{
Console.WriteLine(p);
string line = Console.ReadLine();
return double.Parse(line);
}
private void printSomething(string a) // non-static method
{
Console.WriteLine(a);
}
private static void printfOtherthing(string a) // static method
{
Console.WriteLine(a);
}
}
}
以上所有方法都是在 Program 类里面定义和使用的。
输入8和9后运行,结果如下图所示: