最近写程序,遇到了一个很白痴的问题,记录下来,免得下次忘了。
在C#控制台应用程序里调用自己写的函数的方法有两种:
1. 将调用的函数设置成static
2. 在Main里面实例化program,再调用。
为什么不能在main里面用普通的函数调用方法呢?因为main是静态函数,他调用的本体函数也要求是static
下面是举例:
1 调用静态函数
namespace ConsoleApplication1{ class Program { static void Main(string[] args) { //取得自定义函数的返回值 string msg=aa(); //向控制台输出 System.Console.WriteLine(msg); } //Main是static的,因此aa也要申明为static,否则无法访问 private static string aa() { return "aa"; } }}
2 实例化
using System;using System.Collections.Generic;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { Program p = new Program(); string str = ""; str=p.aa(); Console.WriteLine(str); Console.ReadLine(); } private string aa() { return "aa"; } }}
转载于:https://www.cnblogs.com/alex-13/p/4737317.html
相关资源:数据结构—成绩单生成器