其他分享
首页 > 其他分享> > 09、属性、构造函数与析构函数

09、属性、构造函数与析构函数

作者:互联网

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

  使用set和get关键字

  格式:

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

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

例子:

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()
    {
        //清理非托管资源
    }

 

标签:name,color,与析构,price,09,System,Text,using,构造函数
来源: https://www.cnblogs.com/zytr/p/14730619.html