變量的定義與聲明
string str = "Hello, World!";
class MyClass
{
public int MyProperty;
}
MyClass myObj = new MyClass();
變量的作用域
void MyMethod()
{
int localNum = 10;
// 在這里可以訪問(wèn)localNum
if (true)
{
int anotherLocalNum = 20;
// 在這里可以訪問(wèn)localNum和anotherLocalNum
}
// 在這里無(wú)法訪問(wèn)anotherLocalNum,但是可以訪問(wèn)localNum
}
class MyClass
{
public int memberNum;
void MyMethod()
{
// 在這里可以訪問(wèn)memberNum
memberNum = 30;
}
}
class MyClass
{
public static int staticNum;
}
MyClass.staticNum = 40;
變量的傳遞方式
void ModifyValue(int num)
{
num = 200;
}
int originalNum = 100;
ModifyValue(originalNum);
Console.WriteLine(originalNum); // 輸出100,因?yàn)樵贛odifyValue方法中修改的是副本
class MyClass
{
public int MyProperty;
}
void ModifyObject(MyClass obj)
{
obj.MyProperty = 300;
}
MyClass myObj = new MyClass();
myObj.MyProperty = 100;
ModifyObject(myObj);
Console.WriteLine(myObj.MyProperty); // 輸出300,因?yàn)榭梢酝ㄟ^(guò)引用修改對(duì)象內(nèi)容
?void ModifyValueWithRef(ref int num)
{
num = 500;
}
int originalNumWithRef = 300;
ModifyValueWithRef(ref originalNumWithRef);
Console.WriteLine(originalNumWithRef); // 輸出500,因?yàn)橥ㄟ^(guò)ref修改了變量本身
void GetValues(out int value1, out int value2)
{
value1 = 1;
value2 = 2;
}
int result1, result2;
GetValues(out result1, out result2);
Console.WriteLine(result1 + " " + result2); // 輸出1 2
該文章在 2024/11/27 10:29:38 編輯過(guò)