# C# 語言規範--1.3 變數和參數

int a;

int b = 1;

int a, b = 1;

class Test

{

static void Main() {

int a;

int b = 1;

int c = a + b;   // error, a not yet assigned

...

}

}

using Personnel.Data;

class Employee

{

private static DataSet ds;

public string Name;

public decimal Salary;

...

}

using System;

class Test {

static void F(int p) {

Console.WriteLine("p = {0}", p);

p++;

}

static void Main() {

int a = 1;

Console.WriteLine("pre:  a = {0}", a);

F(a);

Console.WriteLine("post: a = {0}", a);

}

}

pre:  a = 1

p = 1

post: a = 1

“引用參數”用於“by reference”參數傳遞。在此過程中，“引用參數”就是調用者提供的自變數的別名。“引用參數”並不定義自己的變數，而是直接引用原自變數，因此對“引用參數”的修改就將直接影響相應原自變數的值。引用參數用 ref 修飾符來聲明。樣本

using System;

class Test {

static void Swap(ref int a, ref int b) {

int t = a;

a = b;

b = t;

}

static void Main() {

int x = 1;

int y = 2;

Console.WriteLine("pre:  x = {0}, y = {1}", x, y);

Swap(ref x, ref y);

Console.WriteLine("post: x = {0}, y = {1}", x, y);

}

}

pre:  x = 1, y = 2

post: x = 2, y = 1

using System;

class Test {

static void Divide(int a, int b, out int result, out int remainder) {

result = a / b;

remainder = a % b;

}

static void Main() {

for (int i = 1; i < 10; i++)

for (int j = 1; j < 10; j++) {

int ans, r;

Divide(i, j, out ans, out r);

Console.WriteLine("{0} / {1} = {2}r{3}", i, j, ans, r);

}

}

}

using System;

class Test

{

static void F(params int[] args) {

Console.WriteLine("# of arguments: {0}", args.Length);

for (int i = 0; i < args.Length; i++)

Console.WriteLine("\targs[{0}] = {1}", i, args[i]);

}

static void Main() {

F();

F(1);

F(1, 2);

F(1, 2, 3);

F(new int[] {1, 2, 3, 4});

}

}

# of arguments: 0

# of arguments: 1

args[0] = 1

# of arguments: 2

args[0] = 1

args[1] = 2

# of arguments: 3

args[0] = 1

args[1] = 2

args[2] = 3

# of arguments: 4

args[0] = 1

args[1] = 2

args[2] = 3

args[3] = 4

int a = 1, b = 2;

Console.WriteLine("a = {0}, b = {1}", a, b);

namespace System

{

public class Console

{

public static void WriteLine(string s) {...}

public static void WriteLine(string s, object a) {...}

public static void WriteLine(string s, object a, object b) {...}

...

public static void WriteLine(string s, params object[] args) {...}

}

}

## Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD