C#類中欄位field_161019
欄位儲存著一個值型別的例項或者一個指向引用型別的引用。欄位的宣告格式
欄位修飾符 欄位型別 欄位名
修飾符有:new public protected internal, private, static
靜態欄位是屬於類的,通過類名來訪問,例項欄位是屬於物件的,通過物件來訪問。
來個栗子==============================================
執行之後發現number 分別為1,2,但是count都是2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace field
{
class Program
{
class Person
{
public static int count = 0;//宣告靜態欄位
public string name;//一個例項欄位
public int number;
public Person(string name)
{
this.name = name;
count++;
number = count;
}
}
static void Main(string[] args)
{
Person personA = new Person("baby");//建立物件引用,例項化物件
Person personB = new Person("Jack");
Console.Write("第{0}個例項: number = {0}\t", personA.number);
Console.Write("count = {0}\t", Person.count);
Console.WriteLine("name = {0}", personA.name);
Console.Write("第{0}個例項: number = {0}\t", personB.number);
Console.Write("count = {0}\t", Person.count);
Console.WriteLine("name = {0}", personB.name);
}
}
}