zoukankan      html  css  js  c++  java
  • 38属性的种种,只读只写属性、自动属性、静态属性、抽象属性、接口属性

    □ 只读属性

    public class Example
    {
        string name;
        public string Name
        {
            get {return name;}
        }
    }

    □ 只写属性

    public class Example
    {
        string name;
        public string Name
        {
            set {name = value;}
        }
    }

    □ 可读可写属性

    public class Example
    {
        string name;
        public string Name
        {
            get {return name;}
            set {name = value;}
        }
    }

    □ 自动属性

    public class Example
    {
        public string Name {get;set;}
    }

    自动只读属性:

    public class Example
    {
        public string Name{get; private set;}
    }

    自动只写属性:

    public class Example
    {
        public string Name{private get; set;}
    }

    □ 静态属性

    静态属性对应一个静态字段,通常用在"单例模式"中。"单例模式"构造函数必须是私有的。

    public class Example
    {
        private static Example instance = new Example();
        private Example(){}

        public static Example GetInstance
        {
            get {return instance;}
        }
    }

    □ 抽象属性

    抽象类和抽象属性。

    public abstrace class Person
    {
        public abstract string Name{get;set;}
    }

    抽象属性在子类中实现。

    public class Student : Person
    {
        private string name;

        public override string Name
        {
            get {return name;}
            set {name = value;}
        }
    }

    □ 接口属性

    public interface IPerson
    {
        string Name {get;set;}
    }

    public class Student : IPerson
    {
        private string name;

        public string Name
        {
            get {return name;}
            set {name = value;}
        }
    }

    参考资料:
    A Deep Dive into C# Property

  • 相关阅读:
    论知识共享平台
    网虫推荐firefox 4.0插件
    solaris下常见文件压缩/解压方式简单小结—待续中
    Nginx的启动,关闭,重启脚本
    怎样将oracle数据库用户锁住和解锁
    【APACHE】如何重启Apache?
    【MYSQL】解决Mysql直接登录问题(删除匿名用户)
    【PHP】关于set和get函数
    【JMAIL】jmail无法收邮件问题
    【PHP】Class ‘mysqli’ not found 问题
  • 原文地址:https://www.cnblogs.com/darrenji/p/3695188.html
Copyright © 2011-2022 走看看