C# 基础(八)C# get set 以及value 表示什么意思?举例说明

一、基础知识(你只有程序拷贝过去,自己单步执行,才能发现Value是怎样来的)

1、只读

//https://www.cnblogs.com/lixiaolu/p/8214037.html

http://www.cnblogs.com/zl181015/p/9243881.html

2、只写

//https://www.cnblogs.com/lixiaolu/p/8214037.html

http://www.cnblogs.com/zl181015/p/9243881.html

3、读、写

附上代码:

namespace test
{
    class Program
    {
        static int a3 = 3;
        static public int A3
        {
            get { return a3; }
            set { a3 = value; }
        }

        //string str3 = "aaa";
        //public string Str3
        //{
        //    get { return str3; }
        //    set { str3 = value; }
        //}
        static void Main(string[] args)
        {
            Console.WriteLine(a3);
            Console.WriteLine(A3);
            Console.WriteLine();

            A3 = 22;
            Console.WriteLine(a3);
            Console.WriteLine(A3);
            Console.ReadLine();
        }
    }
}

4、Value是什么意思?怎么使用呢?

设置一个断点在A3,你会发现value的值就是等于22:

书本是这样说的:

 

当然,你也可以单部执行A4看看,你会发现 Value的值就是21(与A3同理):

步骤1:A4 = 44, a4 = 44,  Value 不存在

 

步骤2:A4 = 44, a4 = 44,  Value = 21(注意到这里没有,虽然给A4赋值了21,但是它并没有立即更改。这里只有value改变为21

 

步骤3:A4 = 20, a4 = 20,  Value = 21(a4 = 20这一步执行完之后,A4 也变成了 20

步骤4:A4 = 20, a4 = 20,  Value 不存在

附上包含A3、A4的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
        static int a3 = 3;
        static public int A3
        {
            get { return a3; }
            set { a3 = value; }
        }

        static int a4 = 44;
        static public int A4
        {
            get { return a4; }
            set
            {
                if (value > 10)
                {
                    a4 = 20;
                }
                else if (value < 10)
                {
                    a4 = 5555555;
                }
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine(a3);
            Console.WriteLine(A3);
            Console.WriteLine();

            A3 = 22;
            Console.WriteLine(a3);
            Console.WriteLine(A3);

            Console.WriteLine();
            Console.WriteLine(a4);
            Console.WriteLine(A4);
            A4 = 21;
            Console.WriteLine(a4);
            Console.WriteLine(A4);
            Console.ReadLine();
        }
    }
}

 

总结:

1、A4与a4的值,总是相等。

2、若要修改a4,则需要通过A4修改即可。a4的往往通过设置外部属性A4值的方式,然后在A4属性内设置一些条件,来更新a4。

3、Value的值,总是等于外部属性A4的值。

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值