初学C#

  今天开始学习C#,至于为何突然要学习C#,可以解释为需要吧。

  当然,任何一个语言的开始都是hello world,c#也不例外了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Console.WriteLine(
"Hello World!");
        }
    }
}

 

  几个要注意的知识点:

  1、程序定义了一个命名空间Hello,本程序定义的所有类型都位于这个命名空间中,一个程序可以定义多个命名空间。在一个命名空间中可以包含多个类型,但是一个类型只能位于一个命名空间中,不用 的命名空间中相同名字的类型被认为是完全不同的类型。

  2、程序定义了一个类Program,这个类实现了程序的功能。较复杂的程序可能会定义许多类型,由这些类型来共同实现共同的功能。但是,必须要有一个类型包含Main静态方法,这样应用程序才能运行。

  3、 C#的入口方法为Main,首字母是大写。C#中没有全局方法和全局变量的概念呢,所以Main要用作静态方法来实现。而能被Main 调用的方法只能是静态成员方法,或者可以声明另外一个类的一个Public方法,供Main调用。

  

  说了那么多,来看一个例子吧。   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace arr
{
    
class Array
    {
        
public void PrintArray(int Arrlen)
        {
            
int[] arr = new int[Arrlen];
            
for (int i = 0; i < Arrlen; i++)
                arr[i] 
= i+2;
            Console.WriteLine(
"Print array's value");
            
for (int i = 0; i < Arrlen; i++)
                Console.WriteLine(
"arr[{0}] = {1}", i, arr[i]);
            
//注意上面这条语句的输出格式,输出参数是由{i}来控制的
        }
    }
    
class Program
    {
        
static void Main(string[] args)
        {
            Array arr 
= new Array();
            
int i = 1;
            
while (i > 0)
            {
                Console.WriteLine(
"Please enter the array's length");
                i 
= Int32.Parse(Console.ReadLine());//输入
                arr.PrintArray(i);
            }
        }
    }
}

   如果是在Program类写 PrintArray(int Arrlen)函数,那么就要声明为static void PrintArray(int Arrlen) 这样才能正确运行。


posted on 2010-05-18 11:35  Ktyanny Home  阅读(434)  评论(0编辑  收藏  举报

导航