跳至內容

C Sharp/Syntax

維基教科書,自由的教學讀本

C#的面向對象本質,使C#程序高層結構用來定義。

語居[編輯]

int sampleVariable;                           // declaring a variable
sampleVariable = 5;                           // assigning a value
Method();                                     // calling an instance method
SampleClass sampleObject = new SampleClass(); // creating a new instance of a class
sampleObject.ObjectMethod();                  // calling a member function of an object

// executing a "for" loop with an embedded "if" statement 
for (int i = 0; i < upperLimit; i++)
{
    if (SampleClass.SampleStaticMethodReturningBoolean(i))
    {
        sum += sampleObject.SampleMethodReturningInteger(i);
    }
}

語句塊[編輯]

用花括號圍起來的多個語句形成一個語句塊。

private void MyMethod(int integerValue)
{  // This block of code is the body of "MyMethod()"

   // The 'integerValue' integer parameter is accessible to everything in the method

   int methodLevelVariable; // This variable is accessible to everything in the method

   if (integerValue == 2)
   {
      // methodLevelVariable is still accessible here     
  
      int limitedVariable; // This variable is only accessible to code in the, if block

      DoSomeWork(limitedVariable);
   }
   
   // limitedVariable is no longer accessible here
    
}  // Here ends the code block for the body of "MyMethod()".

大小寫敏感[編輯]

C#是大小寫敏感語言。

下述兩個變量myIntegerMyInteger是不同的:

 int myInteger = 3;
 int MyInteger = 5;

C#有個預定義的Console處理命令行操作。

 // Compiler error!
 console.writeline("Hello");

正確寫法:

 Console.WriteLine("Hello");