• 10、属性、构造函数与析构函数


    一、属性可以实现有些值可读可写的控制。

      使用set和get关键字

      格式:

        private string _name;//定义私有变量

        get { return _name; } //可读
        set { _name = value; } //可写

        自动属性

        get:

        set:

    例子:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace _13
    {
        public class product
        {
            private string _name;
            private decimal _price;
            private string _color;
    
            public string name
            {
                get { return _name; }  //可读
                set { _name = value; }  //可写
            }
             
            public decimal price
            {
                get { return _price; }
                set { _price = value; }
            }
       
            public string color
            {
                get { return _color; }
                set { _color = value; }
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace _13
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                
                product p = new product();
                p.name = tb_name.Text;
                p.price = decimal.Parse(tb_price.Text);
                p.color = tb_color.Text;
    
                lbl_name.Text = p.name;
                lbl_price.Text = p.price.ToString();
                lbl_color.Text = p.color;
            }
        }
    }

    二、构造函数

      构造函数在实例化对象时自动调用函数。

      函数名称必须与类名相同

      无返回值类型

      实例化时总会执行构造函数

      如果没有显示申明,C#会自动提供一个默认的空构造函数

     public product(string n,decimal pr,string co)
            {
                _name = n;
                _price = pr;
                _color = co;
            }
      string name = tb_name.Text;
                decimal price = decimal.Parse(tb_price.Text);
                string color = tb_color.Text;
                product p = new product(name,price,color);

    三、析构函数

      清理非托管资源

      不能有参数

      不能有修饰符而且不能被调用

      前缀“~”以示区别

    ~product()
        {
            //清理非托管资源
        }
  • 相关阅读:
    中煜软件,数据库删除凭证
    excel vba获取拼音
    windows server 2012 R2 远程桌面授权模式尚未配置
    用C语言实现窗口抖动
    java修饰符
    Java对象和类
    Java基本语法
    Java开发环境笔记
    我的第一个Java程序和Java简介
    笔记本如何设置插入USB鼠标自动禁用触摸板
  • 原文地址:https://www.cnblogs.com/zytr/p/14730619.html
Copyright © 2020-2023  润新知