首页 > 代码库 > C# 静态方法调用非静态方法
C# 静态方法调用非静态方法
转载:http://blog.csdn.net/seattle1215/article/details/6657814
- 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);
- }
- }
- }
C# 静态方法调用非静态方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。