c# 中属性与字段
2021-07-01 13:04
标签:color eric fir textbox collect cli threading eve private 今天回头学习c# 的基础,看到属性的定义,忽然明白一个简单的道理:字段定义为Private,不需要class 的外部进行访问,那么就可以搞个属性对private 的字段进行get,set, 还有一个理由就是这个private 的字段有时是只读取的,不允许外部赋值写入,那么就只搞个get 的属性OK了 c# 中属性与字段 标签:color eric fir textbox collect cli threading eve private 原文地址:https://www.cnblogs.com/wenjie0904/p/9949897.htmlusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SampleClass
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Add add=new Add();
add.FirstNumber = 9;
//add.SencondNumber = 6; //只读字段赋值报错
int addResult=add.GetAdd();
//textBox1.Text = addResult.ToString();
textBox1.Text = add.SencondNumber.ToString();
}
}
public class Add
{
private int firsNumber;
private int sencondNumber=10;
public Add()
{
}
public int FirstNumber
{
get => firsNumber;
set => firsNumber = value;
}
public int SencondNumber
{
get => sencondNumber; //sendcondNumber 字段只读
//set => sencondNumber = value;
}
public int GetAdd()
{
return firsNumber + sencondNumber;
}
}
}