静态成员和实例成员
类包含成员,成员可以是静态成员或实例成员。
静态成员是属于类级别的,使用static关键字声明,直接通过类名访问;
实例成员是属于对象级别的,需要先实例化类的实例对象,然后通过实例对象访问。
using System;
namespace class_object
{
class Customer
{
public static string Type { get; set; }
public int CustomerId { get; set; }
public string Name { get; set; }
public string GetFullInformation()
{
return $"{CustomerId} - {Name}";
}
public static string GetStaticFormatedType()
{
return $"Customer Type: {Type}";
}
}
class Program
{
static void Main(string[] args)
{
var test = new Customer()
{
CustomerId = 1000,
Name = "CustomerName"
};
// 实例成员访问
Console.WriteLine(test.GetFullInformation());
// 静态成员访问
Customer.Type = "Ooh Type";
Console.WriteLine(Customer.GetStaticFormatedType());
}
}
}
注意:
常量是类级别的,尽管它们没有static修饰符。