关于C#的set和get问题

如何正确的理解get和set呢???

体会set:并没有给_aa赋值,但是_aa里面有值了

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Web;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace ConsoleApplication1
{
    class Program
    {
        public static List<string> bb;
        private static List<string> _aa;
        public static List<string> aa
        {
            
            set
            {
                _aa = value;
                foreach (var dd in value)
                {
                    Console.WriteLine(dd);
                }
                Console.WriteLine("set End");
            }
            get
            {
                return _aa;
            }
        }
        static void Main(string[] args)
        {
            bb = new List<string>();
            bb.Add("jdkdjdk");
            bb.Add("jjjjj");
            bb.Add("iiiiii");
            bb.Add("oooodd");
            aa = bb;
            foreach (var dd in aa)
            {
                Console.WriteLine(dd);
            }
            Console.WriteLine("aa End");
            Console.WriteLine();
            foreach (var dd in _aa)
            {
                Console.WriteLine(dd);
            }
            Console.WriteLine("_aa End");
            Console.Read();
        }
    }
}

体会get:并没有给aa赋值,但能够取到aa里面的值

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Web;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace ConsoleApplication1
{
    class Program
    {
        public static List<string> bb;
        private static List<string> _aa;
        public static List<string> aa
        {
            
            set
            {
                _aa = value;
                foreach (var dd in value)
                {
                    Console.WriteLine(dd);
                }
                Console.WriteLine("set End");
            }
            get
            {
                return _aa;
            }
        }
        static void Main(string[] args)
        {
            bb = new List<string>();
            bb.Add("jdkdjdk");
            bb.Add("jjjjj");
            bb.Add("iiiiii");
            bb.Add("oooodd");
            _aa = bb;
            foreach (var dd in aa)
            {
                Console.WriteLine(dd);
            }
            Console.WriteLine("aa End");
            Console.WriteLine();
            foreach (var dd in _aa)
            {
                Console.WriteLine(dd);
            }
            Console.WriteLine("_aa End");
            Console.Read();
        }
    }
}


个人理解:此时的aa和_aa都指向同一块内存new List<string>(),且set只有在用等号赋值的时候会触发!

发布了32 篇原创文章 · 获赞 7 · 访问量 5万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览