C#教程
第一个程序,按例用“Hello world!”的案例,先从简单的开始,大家可以先读读visual studio的“Hello world!”教程,这是一个控制台程序,我这里写的教程也是控制台程序,但是我可能会添加更复杂的概念。
一、控制台程序:这种程序运行于命令行环境中,不同于具有自己窗口的程序。可以用下面的方法打开命令行,
点击桌面左下角的“开始”按钮,然后想法子找到“运行”并点击它,接下来在输入框中输入cmd命令并运行它。然后就可以在打开的窗口中输入各种命令。
二、用visual studio创建第一个控制台程序
这里是照搬原教程:
创建并运行控制台应用程序
1、启动 Visual Studio。
2、在 “文件”菜单上指向 “新建”,然后单击 “项目”。
3、在 “模板类别”窗格中,展开 “Visual C#”,然后单击 “Windows”。
4、在 “模板”窗格中,单击 “控制台应用程序”。
5、在 “名称”字段中键入项目的名称。 单击 “确定”。
6、新项目出现在 “解决方案资源管理器”中。
7、如果 Program.cs 不是在 “代码编辑器”中打开,则在 “解决方案资源管理器”中右击 Program.cs,然后单击 “查看代码”。
8、用下面的代码替换 Program.cs 的内容。
// A Hello World! program in C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld
{
class Hello
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
9、按 Ctrl+F5 运行项目。命令提示窗口将显示,其中包含行 Hello World!
三、接下来对以上程序进行注释
using System;//指定命名空间System
using System.Collections.Generic;//指定命名空间System.Collections.Generic
using System.Linq;//指定命名空间System.Linq
using System.Text;//指定命名空间System.Text
namespace HelloWorld //namespace定义新命名空间HelloWorld,或者为已存在的//HelloWorld命名空间指定新功能
{
class Hello //定义类
{
static void Main(string[] args) //定义方法,static标明是静态方法,静态方法 //可以直接用类名称调用,而无需实例化
{
Console.WriteLine("Hello World!");
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
四、对以上程序作出一些改动,让它保存一些数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program //类定义
{
private string CurrentTime = "2022年";
Program()
{
}
~Program()
{
}
public string returnTime()
{
return CurrentTime;
}
static void Main(string[] args)
{
Program myProgram = new Program(); //类的实例化
Console.WriteLine(myProgram.returnTime());
}
}
}
名词解释:
对象:某一类事物
类:用class关键字定义的用于描述对象的代码,也可以理解为一种模板
类的实例化:每个特定的对象都具有自己的特征数据,类需要实例化,以用于实际应用。
静态方法:用static标明的是静态方法,静态方法可以直接用类名称调用,而无需实例化
五、实际上,也可以将所有的变量定义在静态方法Main()中,但上面的程序有助于理解静态方法和类之间的关系
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string CurrentTime = "2022年";
Console.WriteLine(CurrentTime);
}
}
}