靜態變量:
靜態變量使用 static 修飾符進行聲明
在所屬類被裝載時創建
通過類進行訪問
所屬類的所有實例的同一靜態變量都是同一個值
非靜態變量:
不帶有 static 修飾符聲明的變量稱做非靜態變量
在類被實例化時創建
通過對象進行訪問
同一個類的不同實例的同一非靜態變量可以是不同的值
示例:
[復制到剪貼板]code:
using system;
using system.collections.generic;
using system.text;
namespace example01
{
class program
{
class class1
{
public static string staticstr = "class";
public string notstaticstr = "obj";
}
static void main(string[] args)
{
//靜態變量通過類進行訪問,該類所有實例的同一靜態變量都是同一個值
console.writeline("class1's staticstr: {0}", class1.staticstr);
class1 tmpobj1 = new class1();
tmpobj1.notstaticstr = "tmpobj1";
class1 tmpobj2 = new class1();
tmpobj2.notstaticstr = "tmpobj2";
//非靜態變量通過對象進行訪問,不同對象的同一非靜態變量可以有不同的值
console.writeline("tmpobj1's notstaticstr: {0}", tmpobj1.notstaticstr);
console.writeline("tmpobj2's notstaticstr: {0}", tmpobj2.notstaticstr);
console.readline();
}
}
}
結果:
class1's staticstr: class
tmpobj1's notstaticstr: tmpobj1
tmpobj2's notstaticstr: tmpobj2
新聞熱點
疑難解答
圖片精選