属性也可以声明为static。静态属性的访问器和所有静态成员一样,具有以下特点。
1、不能访问类的实例成员;
2、不管类是否有实例,它们都是存在的;
3、当从类的外部访问时,必需使用类名引用,而不是实例名
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
//public class Point
//{
// public int X = 1;
// public int Y = 2;
//}
//class Program
//{
// static void Main()
// {
// Point pt1 = new Point();
// Point pt2 = new Point{ X = 5Y = 6 };
// Console.WriteLine("pt1: {0}, {1}", pt1.X, pt1.Y);
// Console.WriteLine("pt2: {0}, {1}", pt1.X, pt2.Y);
// }
//}
class Trivial
{
public static int MyValue { get; set; }
public void PrintValue()
{
Console.WriteLine("Value from inside: {0}",MyValue);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Init Value: {0}",Trivial.MyValue);
Trivial.MyValue = 10;
Console.WriteLine("New Value: {0}",Trivial.MyValue);
Trivial tr = new Trivial();
tr.PrintValue();
Console.Read();
}
}
}