以下内容是学习MSDN上C#开发指导的笔记,温故而知新!
一、一个C#程序可以由一个或者多个文件组成,每个文件可以包含零个或者是多个名字空间,一个名字空间可以包含如下的类型:类、结构、接口、枚举型、委托、或者是其他的名字空间。下面这个就是骨架的图:
// A skeleton of a C# program using System; namespace YourNamespace { class YourClass { }
struct YourStruct { }
interface IYourInterface { }
delegate int YourDelegate();
enum YourEnum { }
namespace YourNestedNamespace { struct YourStruct { } }
class YourMainClass { static void Main(string[] args) { //Your program starts here... } } } |
二、Main函数是.exe应用程序的入口,它用来控制程序的开始和结束。
Main函数的特点:
1)可以返回一个void 或者是int类型的值;
2)必须为static类型,但是不一定要用访问修饰符public;
3) 可以选择带参数或者是不带参数,参数为string类型的数组;
4)必须在一个类中或者是一个结构内部被声明。
5)Main的四中类型:
static void main(){
}
static int main(){
}
static void main(string[] args){
}
static int main(string[] args){
}
6)main函数参数判断
if(args.length == 0){
System.Console.WriteLine("There is no argument.");
}
7)main参数处理:通过用Parse方法或者是Convert类实现。
long num = Int64.Parse(args[0]);
long num = long.Parse(args[0]);
long num = Convert.ToInt64(args[0]);
8)给Main函数传入参数方式:1)命令行方式
2)通过在Solution Explorer选择项目属性----->debug页面中的Command line arguments也可以为它传入参数。
9)指定参数的样式:可以通过 Main 的可选参数来访问通过命令行提供给可执行文件的参数。参数以字符串数组的形式提供。数组的每个元素都包含一个参数。参数之间的空白被移除。例如,下面是对一个假想的可执行文件的命令行调用:
命令行输入 | 传递给 Main 的字符串组 |
---|---|
executable.exe a b c | "a" "b" "c"
|
executable.exe one two | "one" "two"
|
executable.exe “one two” three | "one two" "three" |
例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace TestMain1 { public class Functions { public static long Factorial(int n) {
if((n<0)|| (n>20)){ return -1; } long tempResult = 1; for (int i = 1; i <= n;i++ ) { tempResult*= i; } return tempResult ; } }
class MainClass{
static int Main(string[] args) { if (args.Length == 0) { System.Console.WriteLine("Please enter a numeric argument."); System.Console.WriteLine("Usage:Factorial<num>"); return 1; } int num; bool test = int.TryParse(args[0], out num); if (test == false) { System.Console.WriteLine("Please enter a numeric argument."); System.Console.WriteLine("Usage:Factorial<num>"); return 1; } long result = Functions.Factorial(num);
//print result if (result == -1) { System.Console.WriteLine("Input must be >= 0 and <= 20"); } else { System.Console.WriteLine("The Factorial of {0} if {1}.", num, result); } System.Console.ReadKey(); return 0; } } } |