Unity学前C#:字段 常量 索引器 属性

字段:

静态成员可以有属于自己的静态构造器

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..

当我们需要使用类类型的时候就会报错,所以要用静态只读字段 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值