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

  • 相关阅读:
    linux eclipse cdt make error 127
    centos 安装网络错误
    c++ string 结束符‘00’
    北京市工资交税情况
    gprof参数说明及常见错误
    【转】Eclipse Plugin 在 Console上打印出message
    C++做client Java做客户端传送数据
    word统计章节字数
    【转】Profiling application LLC cache misses under Linux using Perf Events
    【转】eclipse插件开发,调试运行,导出与安装
  • 原文地址:https://www.cnblogs.com/darrenji/p/3695188.html
Copyright © 2011-2022 走看看