zoukankan      html  css  js  c++  java
  • C#篇(二)——属性的实质

    属性的内部实现其实就是方法

    我们平时写的代码:

     class Student
        {
            private int age;
            public int Age
            {
                get
                {
                    return age;
                }
                set
                {
                    age = value;
                }
            }
        }
    

    编译器处理之后的代码:

     class Student
        {
            private int age;
    		//编译器处理之后的代码如下
            public void set_Age(int value)
    		{
    			age = value;
    		}
    		public int get_Age()
    		{
    			return age;
    		}
        }
    

    那么对于自动实现的属性呢?

    源代码:

    	class Student
        {
            //自动实现的属性
            public int Age{ get; set; }
        }
    

    处理之后:

    	class Student
        {
    		private int <>_age;//编译器随机生成的字段(存在一些C#不允许作为标识符的字符但CLR却可以,为了不与用户自定义字段冲突)
            //编译器处理之后的代码如下
            public void set_Age(int value)
    		{
    			<>_age = value;
    		}
    		public int get_Age()
    		{
    			return <>_age;
    		}
        }
    

    到现在你是否真的立即属性的实质了呢?让我们一起来看看下面这个属性吧!

    	class Student
        {
            public int Age
    		{
    			get{
    				return Age;
    			}
    			set{
    				Age = value;
    			}
    		}
        }
    

    属性可以这样写?回答是当然可以,那么如何转化成对应的方法呢?
    若果你真的理解了属性的实质,这就完全不是问题了。

    	class Student
        {
            public void set_Age(int value)
    		{
    			set_Age(value);
    		}
    		public int get_Age()
    		{
    			return get_Age();
    		}        
        }
    

    你会发现这两个方法都是无限递归的死循环,是不是挺有意思的。。。_

  • 相关阅读:
    工程的创建
    scrapy框架简介和基础应用
    移动端数据爬取
    Python网络爬虫之图片懒加载技术、selenium和PhantomJS
    验证码处理
    Python网络爬虫之requests模块
    Python网络爬虫之三种数据解析方式
    Python网络爬虫之requests模块
    scrapy
    基于XML的AOP配置
  • 原文地址:https://www.cnblogs.com/forcheng/p/6483929.html
Copyright © 2011-2022 走看看