首页 > 代码库 > C# 静态方法调用非静态方法

C# 静态方法调用非静态方法

转载:http://blog.csdn.net/seattle1215/article/details/6657814

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace Cash  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             (new Program()).run();  
  13.   
  14.             // writeFee(calculate(dailyRate, workDay));        
  15.             // 对于非 static 方法,若想像上面这样直接调用则会报以下错  
  16.             // Error    1 An object reference is required  
  17.             // for the non-static field, method, or   
  18.             // property ‘Cash.Program.readDouble(string)‘  
  19.                           
  20.             printfOtherthing("static method is called.");        // static 方法可直接调用  
  21.             Program program = new Program();        // 非 static 方法需要先创建一个对象  
  22.                                                     // 然后用对象调用  
  23.             program.printSomething("non-static menthod is called.");  
  24.         }  
  25.   
  26.         public void run()  
  27.         {  
  28.             double dailyRate = readDouble("please enter your rate: ");  
  29.             int workDay = readInt("please enter your days of working: ");  
  30.             writeFee(calculate(dailyRate, workDay));  
  31.         }  
  32.   
  33.         private void writeFee(double p)  
  34.         {  
  35.             Console.WriteLine("The consultant‘s fee is: {0}", p * 1.6);  
  36.         }  
  37.   
  38.         private double calculate(double dailyRate, int workDay)  
  39.         {  
  40.             return dailyRate * workDay;  
  41.         }  
  42.   
  43.         private int readInt(string p)  
  44.         {  
  45.             Console.WriteLine(p);  
  46.             string a = Console.ReadLine();          // 读取输入的字符(readline读取的  
  47.                                                     // 字符都是 string 类型)  
  48.             return int.Parse(a);                    // 把 a 转换为 int 类型,并返回  
  49.         }  
  50.   
  51.         private double readDouble(string p)  
  52.         {  
  53.             Console.WriteLine(p);  
  54.             string line = Console.ReadLine();  
  55.             return double.Parse(line);  
  56.         }  
  57.   
  58.         private void printSomething(string a)       // non-static method  
  59.         {  
  60.             Console.WriteLine(a);  
  61.         }  
  62.   
  63.         private static void printfOtherthing(string a)          // static method  
  64.         {  
  65.             Console.WriteLine(a);  
  66.         }  
  67.     }  
  68. }  

C# 静态方法调用非静态方法