字段:
静态成员可以有属于自己的静态构造器
struct Color
{
public int red;
public int green;
public int blue;
}
class Brush
{
public static readonly Color Color_Default = new Color() { red = 10, green = 10, blue = 10 };
}
或者
struct Color
{
public int red;
public int green;
public int blue;
}
class Brush
{
public static readonly Color Color_Default;
static Brush()
{
Color_Default = new Color() { red = 10,green =10,blue = 10};
}
}
属性:
第一种定义方式:
namespace Hanoi
{
class Programme
{
static void Main(string[] args)
{
try
{
Student stu = new Student();
Student.Age = 101;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
class Student
{
private static int age;
public static int Age
{
set
{
if (age > 100)
throw new Exception("is too large!");
else
age = value;
}
get { return age; }
}
static Student()
{
age = 101;
}
}
注意一下这种定义
private int score;
public int Score
{
get { return score; }
private set { score = value; }
}
这样做的目的是方便内部的函数进行访问而不向外曝露
第二种简便的定义的方式
public int score { get; set; }
索引器:
class Student
{
private Dictionary<string,int> My_Dictionary = new Dictionary<string,int>();
//索引器的定义
public int? this[string index]//返回可以为空值的null
{
get
{
return My_Dictionary[index];
}
set
{
if(value.HasValue == false)
{
throw new Exception("score cannot be null!!!");
}
if(this.My_Dictionary.ContainsKey(index))
{
My_Dictionary[index] = value.Value;
}
else
{
My_Dictionary.Add(index, value.Value);
}
}
}
}
常量
class Student
{
//由于隶属于类,所以必须在定义的时候就被初始化
public const int age = 10;
}
总结
解释一下第四个条,因为常量只能使用基本的类型比如int,double..
当我们需要使用类类型的时候就会报错,所以要用静态只读字段