/*-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->--*/
/*<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--*/
/*-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->--*/
/*<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--*/
/*-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->--*/
/*<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--*/
/*-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->--*/
/*<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--*/
using 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;
using System.IO;//【【【关于文件操作的方法类需要手动添加命名空间
using System.Runtime.Serialization.Formatters.Binary;//【【【BinaryFormatter序列化类的所在
/***************************************************
* 章节: 14文件 15.5 例题-文档序列化
* 题目:1)将一个对象以序列化的形式存储到磁盘;并以去序列化的方式从磁盘读出
* 要点:1)序列化Serialize
* 2)去序列化Deserialize
* 时间:2019、07、06
***************************************************/
namespace EXAMPLE15_5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonWrite_Click(object sender, EventArgs e)
{
MyData mydata = new MyData();
if (textBox1.Text != "") //字符串查空方法1
{
mydata.valInt = Convert.ToInt32(textBox1.Text);
}
else
return;
if (textBox2.Text != string.Empty) //字符串查空方法2
{
mydata.valDou = Convert.ToDouble(textBox2.Text);
}
else
return;
mydata.valStr = textBox3.Text;
FileStream fs =new FileStream("D:\\新建文件夹\\mydata",FileMode.OpenOrCreate,FileAccess.Write);
BinaryFormatter bf =new BinaryFormatter();
bf.Serialize(fs,mydata);//将对象mydata序列化到给定流fs
fs.Close();
}
private void buttonRead_Click(object sender, EventArgs e)
{
MyData mydata = new MyData();
FileStream fs = new FileStream("D:\\新建文件夹\\mydata", FileMode.Open, FileAccess.Read);
BinaryFormatter bf = new BinaryFormatter();
mydata = (MyData)bf.Deserialize(fs);//将指定的流反序列化为对象图形,返回类型为Object,需强制转换为MyData
textBox1.Text = mydata.valInt.ToString();
textBox2.Text = mydata.valDou.ToString();
textBox3.Text = mydata.valStr;
fs.Close();
}
private void buttonClear_Click(object sender, EventArgs e)
{
textBox1.Text = string.Empty;//文本框显示字符串清空方法1
textBox2.Text = ""; //文本框显示字符串清空方法2
textBox3.Clear(); //文本框显示字符串清空方法3
}
}
[Serializable] //指示下面的类MyData可以序列化
public class MyData
{
public int valInt;
public double valDou;
public string valStr;
}
}
using 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;
using System.IO;//【【【关于文件操作的方法类需要手动添加命名空间
/***************************************************
* 章节: 14文件 15.4 例题-文件
* 题目:1)选中不同的驱动器磁盘,分别其中的文件夹,及各个文件
* 要点:1)comboBox下拉控件的使用、列表框控件的使用
* 2)文件目录、文件名获取方法
* 时间:2019、07、06
***************************************************/
namespace EXAMPLE15_4_3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] dirs;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{ //以下拉列表框中的驱动器路径名作为GetDirectories()方法检索目录的入参
try
{
dirs = Directory.GetDirectories(comboBox1.Text); //获取comboBox1.Text指定目录下的所有子目录
listBox1.Items.Clear();//清空目录显示列表框listBox1中的所有显示项
foreach (var n in dirs)
{
listBox1.Items.Add(n);//将各个子目录名添加进目录显示列表框
//listBox1.Items.Add(Path.GetFileNameWithoutExtension(n));//Path.Getxx()方法,可获取指定目录相关信息
}
listBox2.Items.Clear();//清空文件显示列表框listBox2中的所有显示项
foreach (var n in Directory.GetFiles(comboBox1.Text))
{
listBox2.Items.Add(n);//将各个子目录名添加进文件显示列表框
//listBox2.Items.Add(Path.GetFileName(n));
}
}
catch (IOException excep)//当下拉框选中空磁盘的时候,会有一个奇怪的异常产生
{
listBox1.Items.Add("");//在列表框底部先空白一行列表,
listBox1.Items.Add("IOException'name is: " + excep.GetType().Name); //紧接着,着这里打印异常消息提示
listBox1.Items.Add("IOException'message is: " + excep.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{//加载form事件发生时
//将逻辑驱动器加载到comboBox1下拉框中
foreach (var logicDriver in Directory.GetLogicalDrives())//GetLogicalDrives()检索逻辑各个驱动器
{
comboBox1.Items.Add(logicDriver);//将每个逻辑驱动器的名字添加到列表下拉框中
}
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{//双击列表中的某一列表项时,事件发生
if (listBox1.SelectedIndex == -1)//如果双击选中列表项为空时,该值为-1
{ return; }
var currentDir = dirs[listBox1.SelectedIndex];
dirs = Directory.GetDirectories(currentDir);
if (dirs.GetUpperBound(0) == -1)//GetUpperBound(0)获取数组第0维的元素个数,这里是获取子目录是否为空
{
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox1.Items.Add("您双击选中的文件夹目录下的子目录为空!");
return;
}
listBox1.Items.Clear();//清空目录显示列表框listBox1中的所有显示项
foreach (var n in dirs)//【【【数组dirs为空时,不报错,且不执行遍历
{
//listBox1.Items.Add(n);//将各个子目录名添加进目录显示列表框
listBox1.Items.Add(Path.GetFileNameWithoutExtension(n));//Path.Getxx()方法,可获取指定目录相关信息
}
listBox2.Items.Clear();//清空文件显示列表框listBox2中的所有显示项
foreach (var n in Directory.GetFiles(currentDir))
{
//listBox2.Items.Add(n);//将各个子目录名添加进文件显示列表框
listBox2.Items.Add(Path.GetFileName(n));
}
}
}
}
using 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;
using System.IO;//【【【关于文件操作的方法类需要手动添加命名空间
/***************************************************
* 章节: 14文件 15.4 例题-文件
* 题目:1)二进制文件操作BinaryWriter,BinaryReader
* 要点:1)
*
* 时间:2019、07、05
***************************************************/
namespace EXAMPLE15_4_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonWrite_Click(object sender, EventArgs e)
{
SaveFileDialog saDialog = new SaveFileDialog();
if (saDialog.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(saDialog.FileName,FileMode.Create,FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
var valInt = Convert.ToInt32(textBox1.Text);
var valDouble = Convert.ToDouble(textBox2.Text);
var valString = textBox3.Text;
bw.Write(valInt);//写一个二进制数据
bw.Write(valDouble);
bw.Write(valString);//写二进制字符串
bw.Close();
fs.Close();
}
}
private void buttonRead_Click(object sender, EventArgs e)
{
OpenFileDialog opDialog = new OpenFileDialog();
if(opDialog.ShowDialog()==DialogResult.OK)
{
FileStream fs = new FileStream(opDialog.FileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
textBox4.Text = br.ReadInt32().ToString();
textBox5.Text = br.ReadDouble().ToString();//以浮点数的形式读一个二进制数据
textBox6.Text = br.ReadString().ToString();
br.Close();
fs.Close();
//byte[] arr=new byte[100];
//byte[] arr2 = new byte[100];
//fs.Read(arr, 0, 50); //不管是哪种方式读取文件流,读取后,读取指针都向后移动了
//br.Read(arr2, 0, 50);//不管是哪种方式读取文件流,读取后,读取指针都向后移动了
//arr[0] = 0x66;
//arr[1] = 0x67;
//textBox3.Text = "0x"+(arr[1] / 16).ToString() + (arr[1] % 16).ToString();
}
}
}
}
using 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;
using System.IO;//【【【关于文件操作的方法类需要手动添加命名空间
/***************************************************
* 章节: 14文件 15.4 例题-文件
* 题目:1)文件StreamWriter,StreamReader
* 要点:1)
*
* 时间:2019、07、05
***************************************************/
namespace EXAMPLE15_4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonWrite_Click(object sender, EventArgs e)
{
string fileName;
SaveFileDialog sfDialog = new SaveFileDialog();
sfDialog.Filter = "TEXT|*.txt";
if (sfDialog.ShowDialog() == DialogResult.OK)
{
fileName = sfDialog.FileName;
StreamWriter stWriter = new StreamWriter(fileName);
stWriter.Write(textBox1.Text);
stWriter.WriteLine();
stWriter.Close();
}
}
private void buttonRead_Click(object sender, EventArgs e)
{
OpenFileDialog ofDialog = new OpenFileDialog();
ofDialog.Filter = "文本文件|*.txt";
if (ofDialog.ShowDialog() == DialogResult.OK)
{
StreamReader stReader = new StreamReader(ofDialog.FileName);//指定读取文件流的文件来源
textBox1.Text = stReader.ReadToEnd();
stReader.Close();
}
}
}
}
using 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;
/***************************************************
* 章节: 14窗体,对话框和菜单 14.3 例题-菜单
* 题目:1)制作一个菜单栏
* 要点:1)
*
* 时间:2019、07、05
***************************************************/
namespace EXAMPLE14_5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void 拷贝ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Copy();
}
private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Cut();
}
private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Paste();
}
private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Undo();
}
private void 编辑ToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{//编辑框正在下拉事件触发时
if (textBox1.SelectedText == string.Empty)//【【判定被选中的文本是否为空
{
剪切ToolStripMenuItem.Enabled = false;//剪切菜单变灰禁能
}
else
{
剪切ToolStripMenuItem.Enabled = true;//剪切菜单变亮使能
}
}
/* 以下三项上下文菜单需要让textBox1关联contexMenStrip1,方法是:
* textBox1->属性->行为->contexMenStrip->选中contexMenStrip1
*/
private void a拷贝ToolStripMenuItem_Click(object sender, EventArgs e)
{//右键上下文菜单中的拷贝项
textBox1.Copy();
}
private void b剪切ToolStripMenuItem_Click(object sender, EventArgs e)
{//右键上下文菜单中的剪切项
textBox1.Cut();
}
private void c粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
{//右键上下文菜单中的粘贴项
textBox1.Paste();
}
}
}
using 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;
/***************************************************
* 章节: 14窗体,对话框和菜单 14.3 例题-对话框
* 题目:1)通过一个按钮进入一个目录,选择打开/保存一个文件
* 要点:1)文件夹打开对话框、文件夹保存对话框、
* 文件夹浏览对话框、文件夹颜色对话框
* 时间:2019、07、04
***************************************************/
namespace EXAMPLE14_3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string openfilename;
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog fsDialog = new OpenFileDialog();
fsDialog.Filter = "文本文件|*.pdf;*.txt|微软文件|*.doc";//设置对话过滤显示出的文件类型,文本文件--*.pdf;*.txt
if (fsDialog.ShowDialog() == DialogResult.OK)
{
openfilename = fsDialog.FileName;
textBoxOpen.Text = openfilename;//将打开的文件路径名显示到文本框控件
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfDialog = new SaveFileDialog();
sfDialog.Filter = "文本文件|*.pdf;*.c|EXCEL文件|*.xls";//设置文件保存类型
if (sfDialog.ShowDialog() == DialogResult.OK)
{
textBoxSave.Text = sfDialog.FileName;//将保存的文件路径名显示到文本框控件
}
}
private void buttonBrows_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbDialog = new FolderBrowserDialog();
if (fbDialog.ShowDialog() == DialogResult.OK)
{
textBoxBrows.Text = fbDialog.SelectedPath;//SelectedPath:浏览选中的文件夹的路径名
}
}
private void buttonColor_Click(object sender, EventArgs e)
{
ColorDialog colorDialog = new ColorDialog();
if (colorDialog.ShowDialog() == DialogResult.OK)
{
textBoxColor.BackColor = colorDialog.Color;//将获取选中的颜色作为文本框的背景色
}
}
private void buttonFont_Click(object sender, EventArgs e)
{
FontDialog fd = new FontDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
textBoxFont.Font = fd.Font;//将获取的字体类型设置为文本框的字体类型
textBoxFont.Text = "这是您刚刚设置的字体类型,that's your choice!";
}
}
}
}
/*-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->--*/
using 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 EXAMPLE14_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyForm2 myform2 = new MyForm2();
if (radioButton1.Checked)//检测单选控件1是否被选中
{
myform2.DetailText = "详细的日期:\r\n" +
"2019年7月4日 14:26 ";
}
if (radioButton2.Checked)//检测单选控件2是否被选中
{
myform2.DetailText = "详细的内容:\r\n" +
"1、国务院常务会议3日召开,支持跨境电商等新业态发展;\r\n" +
"2、国家移民管理局3日表示,海南将实施更加开放的免签入境政策;\r\n" +
"3、工信部日前发布一季度电信服务质量通告显示。";
}
myform2.Show();//【【【Show()显示出第二个窗体myform2--只显示后直接返回
}
private void button2_Click(object sender, EventArgs e)
{
MyForm3 myform3 = new MyForm3();
if (DialogResult.OK == myform3.ShowDialog()) //【【【ShowDialog()显示出第三个窗体myform3--该窗体为对话窗体,需要手动关闭或设置返回
{//返回DialogResult.OK,表示窗体myform3退出时,是点击了确认按钮
textBoxNAME.Text = myform3.MyName;
textBoxAGE.Text = myform3.Age.ToString();
//textBoxAGE.Text = Convert.ToString(myform3.Age); //或者写成这样转换
}
}
}
}
using 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 EXAMPLE14_2
{
public partial class MyForm2 : Form
{
public MyForm2()
{
InitializeComponent();
}
public string DetailText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
}
using 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 EXAMPLE14_2
{
public partial class MyForm3 : Form
{
public MyForm3()
{
InitializeComponent();
}
public string MyName { get; set; }
public int Age { get; set; }
private void buttonOK_Click(object sender, EventArgs e)
{
if (textBoxName.Text != string.Empty)
MyName = textBoxName.Text;
if (textBoxAge.Text != string.Empty) //【【【防止年龄值为空时,
Age = Convert.ToInt32(textBoxAge.Text);//值转换执行将异常
//Close();//【【【关闭MyForm3对话框窗体方法一 //该窗体为对话窗体,需要手动关闭或设置返回
//【【【关闭MyForm3对话框窗体方法二:设置返回,将buttonOK属性->行为->DialogResult项值设置为OK
}
private void buttonCancel_Click(object sender, EventArgs e)
{
}
}
}
/*<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--*/
using 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 EXAMPLE13_3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Point> listPoint = new List<Point>(300);
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
Point p = new Point(e.X, e.Y);
listPoint.Add(p);//记录鼠标单击过的点
Invalidate();
Graphics g = CreateGraphics();
SolidBrush blueBrush = new SolidBrush(Color.Blue);
g.FillEllipse(blueBrush, new Rectangle(e.X - 20, e.Y - 20, 40, 40));//画出该点
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
//Graphics g = CreateGraphics();
Graphics g = e.Graphics;
SolidBrush blueBrush = new SolidBrush(Color.Blue);
Pen blackPen = new Pen(Color.Black, 2);
for (int i = 0; i < listPoint.Count; i++)//窗口缩小重新打开时,重绘所有点
{
g.FillEllipse(blueBrush, new Rectangle(listPoint[i].X - 20, listPoint[i].Y - 20, 40, 40));
if (i < listPoint.Count - 1)
g.DrawLine(blackPen, listPoint[i], listPoint[i + 1]);//连接两个点
}
}
}
}
using 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 EXAMPLE13_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Random r = new Random();
Graphics g = e.Graphics;
Pen redPen = new Pen(Color.LightBlue, 2);//定义一个画笔,颜色LightBlue,线宽2
g.DrawLine(redPen, 0, 0, 300, 500);
for (int i = 0; i < 100; i++)
{
var x1 = r.Next(this.Width);
var x2 = r.Next(this.Width);
var y1 = r.Next(this.Width);
var y2 = r.Next(this.Width);
var colorR = r.Next(256);
var colorG = r.Next(256);
var colorB = r.Next(256);
Pen myPen = new Pen(Color.FromArgb(colorR, colorG, colorB));//myPen三原色随机组合
g.DrawLine(redPen, x1, y1, x2, y2);
g.DrawLine(myPen, x1, y2, x2, y1);
}
}
}
}
using 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 EXAMPLE12_7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.MouseWheel += panel1_MouseWheel;
}
private void panel1_MouseWheel(object sender, MouseEventArgs e)
{
//throw new NotImplementedException();
textBox1.Text += "E:Delta=" + e.Delta.ToString() + " ";
}
private void panel1_MouseDown(object sender, MouseEventArgs e)//鼠标三个键按下事件
{
if (e.Button == MouseButtons.Left)//判断是否为鼠标左键按下
{
textBox1.Clear();//清除文本框中的显示数据
textBox1.Text = "MouseLocation X:" + e.X.ToString() +
" MouseLocation Y:" + e.Y.ToString();//打印鼠标按下处对于panel1区域的横纵坐标
textBox1.Text += " MouseButtons: LEFT;";
}
}
private void panel1_MouseHover(object sender, EventArgs e)
{
textBox1.Text += " MouseHover;";
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{//【【【【需要将From->杂项->KeyPreview属性设置为True,该事件才能正常提示相关文本消息
textBox1.Text +=
" Alt: " + (e.Alt ? "Yes" : "NO") + //判断ALT键是否已经被按下
" Control: " + (e.Control ? "Yes" : "NO") +
" Shift: " + (e.Shift ? "Yes" : "NO") + ";";
textBox1.Text += " KeyDown:" + e.KeyCode.ToString() + ";"; //打印键值
if (Keys.M == e.KeyCode)//Keys枚举类型,此处判断按下按键是否为枚举类中的M键
{
textBox1.Text += " M key was pressed!";
}
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)//该事件不能检测"F1到F12"等
{ //也不能检测Alt,Control,Shift,Cpaslock等等按键
//【【【【需要将From->杂项->KeyPreview属性设置为True,该事件才能正常提示相关文本消息
textBox1.Text += " KeyPress:" + e.KeyChar + ";";
}
}
}
using 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 EXAMPLE12_6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)//加载form框时图片显示区pictureBox1做一个初始化显示
{
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;//PictureBoxSizeMode.Zoom;Zoom为一图片显示方式,居中,缩放等等
pictureBox1.ImageLocation = @"C:\Users\Administrator.USER-20140101DA\Desktop\test\EXAMPLE01\EXAMPLE12_6\图片\TabControl(控件)1.png";
}
bool FlgClick = false;
private void buttonGo_Click(object sender, EventArgs e)//点击“开始显示图片”按钮触发事件-开始计时
{
FlgClick = FlgClick == true ? false : true;
if (FlgClick == false)
timer1.Enabled = false;//关闭定时器
else
timer1.Enabled = true;
}
int index = 0;
private void timer1_Tick(object sender, EventArgs e)//定时事件TICK产生
{
//更新进度条显示,并切换图片显示
var incr=Convert.ToInt32(numericUpDown.Value);//获取数字调节控件当前值
if (incr + progressBar.Value <= progressBar.Maximum)//以incr为步长调节进度条显示位置
progressBar.Value += incr;//progressBar.Value的上限progressBar.Maximum是可取得
else
{
FlgClick = false; timer1.Enabled = false;//关闭定时器
progressBar.Value = 0; //进度条清零
//index = 0;//复位,显示第0张图片
}
index = (index + 1) % 5;
if (0 == incr)
index = 0;
switch (index)
{
case 0:
//【【【【加载本地资源--加载图片的绝对路径
//pictureBox1.ImageLocation =
//@"C:\Users\Administrator.USER-20140101DA\Desktop\test\EXAMPLE01\EXAMPLE12_6\图片\TabControl(控件)1.png";
//【【【【加载项目资源--设置方法:解决方案资源管理器->项目->右键点击->属性->资源->图像->添加资源
pictureBox1.Image = Properties.Resources.TabControl_控件_1;
break;
case 1:
//pictureBox1.ImageLocation =
//@"C:\Users\Administrator.USER-20140101DA\Desktop\test\EXAMPLE01\EXAMPLE12_6\图片\TabControl(控件)2.png";
pictureBox1.Image = Properties.Resources.TabControl_控件_2;
break;
case 2:
//pictureBox1.ImageLocation =
//@"C:\Users\Administrator.USER-20140101DA\Desktop\test\EXAMPLE01\EXAMPLE12_6\图片\TreeView(控件)9.png";
pictureBox1.Image = Properties.Resources.TreeView_控件_9;
break;
case 3:
//pictureBox1.ImageLocation =
//@"C:\Users\Administrator.USER-20140101DA\Desktop\test\EXAMPLE01\EXAMPLE12_6\图片\TreeView(控件)10.png";
pictureBox1.Image = Properties.Resources.TreeView_控件_10;
break;
case 4:
//pictureBox1.ImageLocation =
//@"C:\Users\Administrator.USER-20140101DA\Desktop\test\EXAMPLE01\EXAMPLE12_6\图片\TreeView(控件)2.png";
pictureBox1.Image = Properties.Resources.TreeView_控件_2;
break;
}
}
}
}
using 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 EXAMPLE12_5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (textBoxInput.Text != string.Empty)//如果输入框不为空,点击添加按钮时
{ //要将数据添加到列表框
listBox1.Items.Add(textBoxInput.Text);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)//列表框中选中的项发生变化时,该事件产生
{
if (listBox1.SelectedIndex >= 0 &&
listBox1.SelectedIndex < listBox1.Items.Count)//只有在鼠标选中某一项时,才操作,没选中是,值为-1
//textBoxInput.Text = Convert.ToString(listBox1.Items[listBox1.SelectedIndex]);//转换为字符串方法一
textBoxInput.Text = (listBox1.Items[listBox1.SelectedIndex]).ToString(); //转换为字符串方法二
}
private void buttonDel_Click(object sender, EventArgs e)
{
if(listBox1.SelectedIndex>=0 &&
listBox1.SelectedIndex<listBox1.Items.Count)//只有在鼠标选中某一项时,才操作,没选中是,值为-1
listBox1.Items.RemoveAt(listBox1.SelectedIndex);//点击删除按钮,删除列表中的某项
}
}
}
using 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 EXAMPLE12_4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
double baseMoney = Convert.ToDouble(textBoxBase.Text);
var year = Convert.ToInt32(textBoxYear.Text);
var interest = Convert.ToDecimal(textBoxInterest.Text);
textBoxSum.Text=
(baseMoney *
Math.Pow(Convert.ToDouble(1 + interest), year))//返回(1+interest)的year次幂
.ToString();//将最终结果转换为字符串
}
}
}
using 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 EXAMPLE12_2_copy
{
public partial class FormTextShow : Form //partial表示下面的代码只是Form类的部分代码
{
public FormTextShow()
{
InitializeComponent();
}
private void textBoxInput_TextChanged(object sender, EventArgs e)//TextChanged事件触发时执行程序(又名“消息处理程序”)
{
textBoxOutput.Text = textBoxInput.Text;//用户自主代码段--此处将输入文本框中的字符串拷贝到输出文本框
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
private void label1_Click_2(object sender, EventArgs e)
{
}
}
}
/*-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->-->--*/
//以上部分为窗体应用程序
//以下部分为控制台应用程序
/*<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--<--*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 11泛型和委托 11.5 例题-多播委托
* 题目:
* 1)
* 要点:
* 1)委托对象可以使用"+"运算符进行合并
* 2)"-"运算符可用于从合并委托中移除组件委托
* 3)只有相同类型的委托可被合并
* 4)调用多播委托时,方法将按照添加顺序依次调用
* 时间:2019、06、25
***************************************************/
namespace EXAMPLE11_5
{
class Program
{
static void Main(string[] args)
{
Draw d1 = new Draw() { Stuid = 1, PenColor = ConsoleColor.Yellow };//【【【【对属性赋初值
Draw d2 = new Draw() { Stuid = 2, PenColor = ConsoleColor.Red };
Draw d3 = new Draw() { Stuid = 3, PenColor = ConsoleColor.Green };
Console.WriteLine("对象调用方法形式---->");
d1.DrawPicture();
d2.DrawPicture();
d3.DrawPicture();
Console.WriteLine("单播委托形式---->");
Action action1 = new Action(d1.DrawPicture);
Action action2 = new Action(d2.DrawPicture);
Action action3 = new Action(d3.DrawPicture);
action1(); action2(); action3();//调用单播委托
Console.WriteLine("多播委托形式---->");
action1 += action2;//相同类型的委托合并到委托action1
action1 += action3;
action1();//调用多播委托
Console.WriteLine("------");
action1 -= action2;
action1();//调用多播委托
}
}
class Draw
{
public int Stuid { get; set; }
public ConsoleColor PenColor { get; set; }
public void DrawPicture()
{
Console.ForegroundColor = PenColor;
Console.WriteLine("Stuid{0} draw a cat",Stuid);
}
}
}
//对象调用方法形式---->
//Stuid1 draw a cat
//Stuid2 draw a cat
//Stuid3 draw a cat
//单播委托形式---->
//Stuid1 draw a cat
//Stuid2 draw a cat
//Stuid3 draw a cat
//多播委托形式---->
//Stuid1 draw a cat
//Stuid2 draw a cat
//Stuid3 draw a cat
//------
//Stuid1 draw a cat
//Stuid3 draw a cat
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 11泛型和委托 11.4 例题-内置委托类型
* 题目:
* 1)通过一个方法自动识别调用哪个具体的方法
* 要点:
* 2)内置委托类型
* 2.1)
* Action是无返回值的泛型委托
* Action<int,string>表示有传入参数int,string,但无返回值的委托
* Action最多允许16个参数,都没有返回值
* 2.2)
* Func是有返回值的泛型委托
* Func<int>表示无参,返回值为int的委托
* Func<object,string,int>表示入参是object,string,返回值为int的委托
* Func<T1,T2,int>表示入参是T1,T2(泛型),返回值为int的委托
* Func最多允许16个参数,且必须有返回值
* 时间:2019、06、24
***************************************************/
namespace EXAMPLE11_4
{
class Program
{
static void Main(string[] args)
{
Greeting g = new Greeting();
g.SayHello();
g.SayHelloToSomeone("Lily");
Console.WriteLine("-------内置委托类型Action-------------");
Action a1 = new Action(g.SayHello);//无返回值,无参类型的委托
a1();
Action<string> a2 = new Action<string>(g.SayHelloToSomeone);//无返回值,有参类型的委托
a2("Cheng");
Console.WriteLine("-------内置委托类型Func-------------");
Caculate c = new Caculate();
Func<int, int, int> func1 = new Func<int, int, int>(c.Add);
Console.WriteLine("内置委托Func--Add:{0}",func1(10, 5));
Func<int, int, int> func2 = new Func<int, int, int>(c.Sub);
Console.WriteLine("内置委托Func--Sub:{0}", func2(10, 5));
}
}
class Greeting
{
public void SayHello()
{
Console.WriteLine("hello everyone!");
}
public void SayHelloToSomeone(string name)
{
Console.WriteLine("hello, "+name);
}
}
class Caculate
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
}
//hello everyone!
//hello, Lily
//-------内置委托类型Action-------------
//hello everyone!
//hello, Cheng
//-------内置委托类型Func-------------
//内置委托Func--Add:15
//内置委托Func--Sub:5
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 11泛型和委托 11.3 例题-委托的定义
* 题目:
* 1)通过一个方法自动识别调用哪个具体的方法
* 要点: 1)委托:一个方法作为另一个方法的参数,类似于C++的函数指针
* 定义:它定义了方法的类型,使得一个方法可以当做另一个方法的参数进行传递
* 2)内置委托类型
* 2.1)
* Action是无返回值的泛型委托
* Action<int,string>表示有传入参数int,string,但无返回值的委托
* Action最多允许16个参数,都没有返回值
* 2.2)
* Func是有返回值的泛型委托
* Func<int>表示无参,返回值为int的委托
* Func<object,string,int>表示入参是object,string,返回值为int的委托
* Func<T1,T2,int>表示入参是T1,T2(泛型),返回值为int的委托
* Func最多允许16个参数,且必须有返回值
* 时间:2019、06、24
***************************************************/
namespace EXAMPLE11_3
{
class Program
{
static void Main(string[] args)
{
SayHello("Mikiy", EnglishGreeting);//方法名EnglishGreeting作为函数参数
SayHello("林依晨", ChineseGreeting);
Console.WriteLine("---------------------");
//Console.ReadKey();//等待获取任何一个按键按下
Type t = typeof(GreetingDelegate);//t.IsClass可检查一个东东是不是类class
Console.WriteLine(t.IsClass ? "GreetingDelegate是一个类" : "GreetingDelegate不是一个类");
Console.WriteLine("---------------------");
Console.WriteLine("--------实例化委托-------------");
GreetingDelegate gd = new GreetingDelegate(ChineseGreeting);//实例化委托
gd("王麻子");
}
private static void EnglishGreeting(string name)
{
Console.WriteLine("Hello, " + name);
}
private static void ChineseGreeting(string name)
{
Console.WriteLine("您好, " + name);
}
private static void SayHello(string name, GreetingDelegate GreetPeople)
{//此方法接受一个GreetingDelegate类型的方法作为参数
GreetPeople(name);
}
//定义委托,它定义了可以代表的方法的类型//该委托(GreetingDelegate)可以
//被用于引用任何一个有单一string参数,并返回void的方法
public delegate void GreetingDelegate(string name);
}
}
//Hello, Mikiy
//您好, 林依晨
//---------------------
//GreetingDelegate是一个类
//---------------------
//--------实例化委托-------------
//您好, 王麻子
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 11泛型和委托 11.2 例题-泛型示例
* 题目:
* 1)创建3个不同类型的数组,并分别打印各个数组元素
* 要点: 泛型T
* 时间:2019、06、24
***************************************************/
namespace EXAMPLE11_2
{
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3 };
double[] b = { 1.1, 2.2, 3.3 };
char[] c = { 'a', 'b', 'c' };
Display(a);//效果类似于Display(int[] arr)
Display(b);//效果类似于Display(double[] arr)
Display(c);//效果类似于Display(char[] arr)
Stack<int> s = new Stack<int>(10);//通过泛型创建一个int型数组
System.Collections.Stack s1 = new System.Collections.Stack(12);//非泛型的Stack,元素类型object
}
static void Display<T>(T[] arr) //泛型函数,实际上,根据不同类型参数
{ //自动编译为不同的代码
foreach (T k in arr)
{
Console.Write(k);
Console.Write('\t');
}
Console.WriteLine();
}
}
class Stack<Ttype> //定义一个泛型的类
{
private int top; //栈顶
private int bottom; //栈底
private Ttype[] element; //栈空间索引,泛型数组
public Stack(int size)
{
element = new Ttype[size];//开辟泛型数组空间
}
}
}
//1 2 3
//1.1 2.2 3.3
//a b c
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 10异常 10.2 例题-抛出异常
* 题目:
* 1)
* 要点:
* 1)自定义异常
* 时间:2019、06、25
***************************************************/
namespace EXAMPLE10_3
{
class Program
{
static void Main(string[] args)
{
try
{
FFF f = new FFF();
//f.Age = -2; //将抛出异常
f.Age = 2; //不会抛出异常
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally //这里面的语句无论异常是否发生,都将被执行
{
Console.WriteLine("Finally code segment");
}
}
}
public class FFF
{
private int age;
public int Age {
get { return age; }
set {
if (value >= 0)
age = value;
else
{
age = 0;
throw (new MyException());//throw,抛出异常--人为触发异常
//throw (new MyException("构造函数赋初值出错!"));//调用不同的异常的构造函数
}
}
}
}
public class MyException : Exception
{
//不带参自定义异常
public MyException() : base("Age should be over zero!") { }
//带一个字符串参数
public MyException(string message) : base(message) { }
//带一个字符串参数和一个exception参数,指明该异常是由另一个异常触发
public MyException(string message, Exception excep) : base(message, excep) { }
}
}
/* 执行代码为 f.Age = -2; //将抛出异常 */
//Age should be over zero!
//Finally code segment
//请按任意键继续. . .
/* 执行代码为 f.Age = 2; //不会抛出异常 */
//Finally code segment
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 10异常 10.2 例题-异常
* 题目:
* 1)除数为0时,捕获异常
* 2)格式不正确时,捕获异常
* 要点:
* 1)
* 时间:2019、06、25
***************************************************/
namespace EXAMPLE10_2
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请输入除法运算的两个整数:");
try
{
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = a / b;//异常会在这里产生
Console.WriteLine(c);
break;//代码运行到这里,说明无异常
}
catch (DivideByZeroException excep)//捕获DivideByZeroException异常(被零除异常)
{
Console.WriteLine(excep.Message);//打印异常消息提示
Console.WriteLine("Try again!");
}
catch (FormatException excep)捕获FormatException异常(格式异常)
{
Console.WriteLine(excep.Message);
Console.WriteLine("Try again!");
}
}
}
}
}
//请输入除法运算的两个整数:
//10
//0
//尝试除以零。
//Try again!
//请输入除法运算的两个整数:
//12
//y
//输入字符串的格式不正确。
//Try again!
//请输入除法运算的两个整数:
//12
//2
//6
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 9多态 9.6 例题-多继承-员工工资
* 题目:
* 1)固定工:每周工资一样,与工作事件长短无关,由SalariedEmployee类
* 2)计时工:按时计酬,超过40小时,算加班工资,由HourlyEmployee类实现
* 3)销售工:在底薪之上增加销售百分比。在本期内,公司准备对底薪
* 雇佣工加薪10%,由CommissionEmployee类实现
* 4)底薪+销售员工:BasePlusCommissionEmployee
* 要点: 关键字 abstract override
* 时间:2019、06、22
***************************************************/
namespace EXAMPLE9_6
{
class Program
{
static void Main(string[] args)
{
SalariedEmployee se = new SalariedEmployee("Jack","1111",100);
display(se);
HourlyEmployee he = new HourlyEmployee("Rose", "2222", 5.3m, 50m);
display(he);
CommissionEmployee ce = new CommissionEmployee("Linda", "3333", 12035m, 0.1m);
display(ce);
BasePlusCommissionEmployee be = new BasePlusCommissionEmployee("Miki", "4444", 10243m, 0.1m,100);
display(be);
Console.WriteLine("----------------");
Employee[] employ =new Employee[4];
employ[0]=se; employ[1]=he; employ[2]=ce; employ[3]=be;
foreach (var current in employ)//等效为foreach (Employee current in employ)
{
if (current is BasePlusCommissionEmployee) //【【【【is语法(相等判断)可判断某个子类到底属于哪一种子类
Console.WriteLine("This is BasePlusCommissionEmployee--->");
display(current);
}
}
static public void display(Employee e)
{
Console.WriteLine(e);
}
}
public abstract class Employee
{
public string Name { get; private set; }
public string SSD { get; private set; }
public Employee(string name, string ssd)
{
Name = name;
SSD = ssd;
}
public override string ToString()
{
return string.Format("{0}'s ssd is:{1}", Name, SSD);
}
public abstract decimal Earning();//【【【【抽象方法,计算器员工工资-无须实现方法体
}
public class SalariedEmployee:Employee
{
private decimal weekSalary;
public decimal WeekSalary
{
get {
return weekSalary;
}
set {
weekSalary = value >= 0 ? value : 0;
}
}
public SalariedEmployee(string name, string ssd,decimal salara):base(name,ssd)
{
WeekSalary = salara;
}
public override decimal Earning()//【【【【抽象方法,在子类实现方法体
{
return WeekSalary;
}
public override string ToString()//重写子类SalariedEmployee的ToString方法
{
return string.Format("SalariedEmployee: {0}\n"
+"salara is{1:C}", base.ToString(), Earning());//【【 C 或 c 货币格式输出
}
}
public class HourlyEmployee : Employee
{
private decimal wage;//小时工资
public decimal hour; //工作小时
private decimal Wage
{
get{return wage;}
set{wage = value >= 0 ? value : 0;}
}
private decimal Hour
{
get{return hour;}
set{hour = value >= 0 ? value : 0;}
}
public HourlyEmployee(string name, string ssd, decimal wage, decimal hours)
: base(name, ssd)
{
Wage = wage;
Hour = hours;
}
public override decimal Earning()//【【【【抽象方法,在子类实现方法体
{
if (Hour <= 40)
return Wage * Hour;
else
return (40 * Wage) + (Hour - 40) * (1.5m * Wage);
}
public override string ToString()//重写子类SalariedEmployee的ToString方法
{
return string.Format("HourlyEmployee: {0}\n"+ //和C语言不同,连续字符串换行,用“+”连接
"wage is {1},work hours is {2},"+
" salara is{3:C}", base.ToString(), Wage, Hour,Earning());//【【 C 或 c 货币格式输出
}
}
public class CommissionEmployee : Employee
{
private decimal grossSale;//销售总额
public decimal moneyRate; //提成百分比
private decimal GrossSale
{
get { return grossSale; }
set { grossSale = value >= 0 ? value : 0; }
}
private decimal MoneyRate
{
get { return moneyRate; }
set { moneyRate = value >= 0 ? value : 0; }
}
public CommissionEmployee(string name, string ssd, decimal sale, decimal rate)
: base(name, ssd)
{
GrossSale = sale;
MoneyRate = rate;
}
public override decimal Earning()//【【【【抽象方法,在子类实现方法体
{
return GrossSale * MoneyRate;
}
public override string ToString()//重写子类SalariedEmployee的ToString方法
{
return string.Format("CommissionEmployee: {0}\n" + //和C语言不同,连续字符串换行,用“+”连接
"GrossSale is {1},MoneyRate is {2}," +
" salara is{3:C}", base.ToString(), GrossSale, MoneyRate, Earning());//【【 C 或 c 货币格式输出
}
}
public class BasePlusCommissionEmployee : CommissionEmployee
{
private decimal baseSalary;//底薪
private decimal BaseSalary
{
get { return baseSalary; }
set { baseSalary = value >= 0 ? value : 0; }
}
public BasePlusCommissionEmployee(string name, string ssd, decimal sale, decimal rate, decimal salary)
: base(name, ssd, sale,rate)
{
BaseSalary = salary;
}
public override decimal Earning()//【【【【抽象方法,在子类实现方法体
{
return base.Earning()+BaseSalary;//销售工资+底薪
}
public override string ToString()//重写子类SalariedEmployee的ToString方法
{
return string.Format("BasePlusCommissionEmployee: {0}\n" + //和C语言不同,连续字符串换行,用“+”连接
"BaseSalary is {1:c}, total salara is {2:C}",
base.ToString(),BaseSalary,Earning());//【【 C 或 c 货币格式输出
}
}
}
//SalariedEmployee: Jack's ssd is:1111
//salara is¥100.00
//HourlyEmployee: Rose's ssd is:2222
//wage is 5.3,work hours is 50, salara is¥291.50
//CommissionEmployee: Linda's ssd is:3333
//GrossSale is 12035,MoneyRate is 0.1, salara is¥1,203.50
//BasePlusCommissionEmployee: CommissionEmployee: Miki's ssd is:4444
//GrossSale is 10243,MoneyRate is 0.1, salara is¥1,124.30
//BaseSalary is ¥100.00, total salara is ¥1,124.30
//----------------
//SalariedEmployee: Jack's ssd is:1111
//salara is¥100.00
//HourlyEmployee: Rose's ssd is:2222
//wage is 5.3,work hours is 50, salara is¥291.50
//CommissionEmployee: Linda's ssd is:3333
//GrossSale is 12035,MoneyRate is 0.1, salara is¥1,203.50
//This is BasePlusCommissionEmployee--->
//BasePlusCommissionEmployee: CommissionEmployee: Miki's ssd is:4444
//GrossSale is 10243,MoneyRate is 0.1, salara is¥1,124.30 //【【【神奇】】】父类的Earning方法打印出子类的计算结果
//BaseSalary is ¥100.00, total salara is ¥1,124.30 //子类Earning计算出总工资
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 9多态 9.4 例题-接口
* 题目:创建一个接口IPortA
* 1)派生一个子接口IPortB
* 2)从子接口IPortB派生一个子类AA
* 要点: 关键字operator
* 时间:2019、06、21
***************************************************/
namespace EXAMPLE9_5
{
class Program
{
static void Main(string[] args)
{
AA a = new AA();
a.DisplayA();
a.DisplayB();
}
}
public interface IPortA
{
void DisplayA();//接口类的任何方法,属性,事件索引器默认public型,且不可更改
}
public interface IPortB:IPortA
{
void DisplayB();//接口类的任何方法,属性,事件索引器默认public型,且不可更改
}
public class AA : IPortB, IPortA //多继承,有多个父类,或者写成这样也行:public class AA : IPortB
{
//子类AA必须要实现父类接口中的所有方法】】】】
public void DisplayA()
{
Console.WriteLine("IPortA");
}
public void DisplayB()
{
Console.WriteLine("IPortB");
}
}
}
//IPortA
//IPortB
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 9多态 9.4 例题-运算符重载
* 题目:创建一个复数类,可以实现两个复数的加法
* 1)
* 2)
* 要点: 关键字operator
* 时间:2019、06、21
***************************************************/
namespace EXAMPLE9_4
{
class Program
{
static void Main(string[] args)
{
Complex x1 = new Complex(1,2);
Complex x2 = new Complex(2, 3);
Console.WriteLine("复数x1:");
Console.WriteLine(x1);
Console.WriteLine("复数x2:");
Console.WriteLine(x2);
Console.WriteLine("方法1,复数x3=x1+x2:");
Complex x3 = x1.Add(x2);
Console.WriteLine(x3);
Console.WriteLine("方法2,复数x4=x1+x2:");
Complex x4 = Complex.Add(x1,x2);
Console.WriteLine(x4);
Console.WriteLine("方法3,复数x5=x1+x2:");
Complex x5 = x1+x2;
Console.WriteLine(x5);
}
}
public class Complex
{
private double real;
private double image;
public Complex(double r, double i)
{
real = r;
image = i;
}
public void Set(double r, double i)
{
real = r;
image = i;
}
public override string ToString()
{
return string.Format("{0}+{1}i", real, image); //返回一个带格式的合成字符串
}
public Complex Add(Complex x)
{
Complex t = new Complex(0,0);
t.real = x.real + real;
t.image = x.image + image;
return t;
}
public static Complex Add(Complex x1, Complex x2) //静态公有访问的Add方法,可与上一个方法重名】】】】
{
Complex t = new Complex(0, 0);
t.real = x1.real + x2.real;
t.image = x1.image + x2.image;
return t;
}
public static Complex operator +(Complex x1, Complex x2) //C#运算符重载只能在静态方法中,而C++不限制】】】】
{
Complex t = new Complex(0, 0);
t.real = x1.real + x2.real;
t.image = x1.image + x2.image;
return t;
}
}
}
//复数x1:
//1+2i
//复数x2:
//2+3i
//方法1,复数x3=x1+x2:
//3+5i
//方法2,复数x4=x1+x2:
//3+5i
//方法3,复数x5=x1+x2:
//3+5i
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 9多态 9.3 例题-多态--宠物
* 题目:创建一个继承层次,体现出多态的使用意义。
* 1)创建一个父类-宠物类Pet,包含字段Name,Age,
* 包含方法Speak(),体现宠物的叫声模样
* 2)创建一个子类-Cat,继承来自父类的虚方法virtual Speak,
* 或者抽象方法abstract Speak
* 要点: 关键字virtual override abstract
* 时间:2019、06、20
***************************************************/
namespace EXAMPLE9_3
{
class Program
{
static void Main(string[] args)
{
//Pet p = new Pet("pet:",12);
//Speak(p);
Cat c = new Cat("cat:",10);
Speak(c);
Console.WriteLine("----------");
Dog d = new Dog("dog:",5);
Speak(d);
}
static void Speak(Pet p)
{
Console.WriteLine(p);//Pet类型的p将被系统通过ToString()
//自动转换为string类型数据,而ToString已经被我重写,
//且返回Pet下的Name字段
p.Speak(); //打印宠物叫声
if (p is Pet) //该语法可识别类的类别
{
Console.WriteLine("This is pet!");//Cat属于Pet,所以,该行将被打印
}
if (p is Cat) //该语法可识别类的类别
{
Console.WriteLine("This is cat!");
}
else if (p is Dog)
{
Console.WriteLine("This is dog!");
}
}
}
public abstract class Pet //abstract抽象类
{
public string Name { get; private set; }//set属性为私有访问
public int Age { get; private set; }
public Pet(string n, int a)
{
Name = n;
Age = a;
}
//public virtual void Speak()
//{
// Console.WriteLine("Speak:xxxxx"); ;
//}
public abstract void Speak(); //abstract抽象方法必须存在于抽象类,无需写方法体
//【【【【【【【【【【【【【【
public override string ToString() //重写ToString方法
{
return Name;
}
}
public sealed class Cat : Pet //密封修饰符sealed,指明Cat类不允许再向下派生
{
public Cat(string n,int a):base(n,a)
{ }
public override void Speak() //【【【【【【【【【【【【【【
{
Console.WriteLine("MIAO MIAO...");
}
}
public class Dog : Pet
{
public Dog(string n, int a) : base(n, a)
{ }
public override void Speak() //【【【【【【【【【【【【【【
{
Console.WriteLine("WANG WANG...");
}
}
}
//cat:
//MIAO MIAO...
//This is pet!
//This is cat!
//----------
//dog:
//WANG WANG...
//This is pet!
//This is dog!
//请按任意键继续. . .
/******以下是用virtual范例**********
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
///***
// * 章节: 9多态 9.3 例题-多态--宠物
// * 题目:创建一个继承层次,体现出多态的使用意义。
// * 1)创建一个父类-宠物类Pet,包含字段Name,Age,
// * 包含方法Speak(),体现宠物的叫声模样
// * 2)创建一个子类-
// * 3)创建一个子类-
// * 要点: 关键字virtual override
// * 时间:2019、06、20
// ***
namespace EXAMPLE9_3
{
class Program
{
static void Main(string[] args)
{
Pet p = new Pet("pet:",12);
Speak(p);
Cat c = new Cat("cat:",10);
Speak(c);
}
static void Speak(Pet p)
{
Console.WriteLine(p);//Pet类型的p将被系统通过ToString()
//自动转换为string类型数据,而ToString已经被我重写,
//且返回Pet下的Name字段
p.Speak();
}
}
public class Pet
{
public string Name { get; private set; }//set属性为私有访问
public int Age { get; private set; }
public Pet(string n, int a)
{
Name = n;
Age = a;
}
public virtual void Speak() //【【【【【【【【【【【【【【
{
Console.WriteLine("Speak:xxxxx"); ;
}
public override string ToString() //重写ToString方法
{
return Name;
}
}
public class Cat : Pet
{
public Cat(string n,int a):base(n,a)
{ }
public override void Speak() //【【【【【【【【【【【【【【
{
Console.WriteLine("MIAO MIAO...");
}
}
}
//pet:
//Speak:xxxxx
//cat:
//MIAO MIAO...
//请按任意键继续. . .
*****************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 9多态 9.2 例题-多态
* 题目:创建一个继承层次,体现出多态的使用意义。
* 1)创建一个父类-圆,Circle,可计算圆面积Area()
* 2)创建一个子类-球Sphere,继承父类的Area,但要重写Area,
* 求出求的面积
* 3)创建一个子类-圆柱Cylinder,继承父类的Area,但要重写Area,
* 求出圆柱的面积
* 要点: 关键字virtual override
* 时间:2019、06、20
***************************************************/
namespace EXAMPLE9_2
{
class Program
{
static void Main(string[] args)
{
Circle c = new Circle(1);
Console.WriteLine("圆的面积:{0:0.00}", Area(c));
Sphere s = new Sphere(1);
Console.WriteLine("球的面积:{0:0.00}", Area(s));
Cylinder y = new Cylinder(1,2);
Console.WriteLine("圆柱的面积:{0:0.00}", Area(y));
}
static double Area(Circle c) //【【【神奇的用法,共用静态函数Area可以和父类,子类的方法名一样】】
{
return c.Area();//----【【如果父类子类没有相关修饰符修饰,则此处,调用的方法都会默认调用父类的Area
}
}
public class Circle
{
protected double radius;
public Circle(double r)
{
radius = r >= 0 ? r : 0;
}
public virtual double Area() //虚基类
{
return Math.PI * radius * radius;
}
}
public class Sphere:Circle
{
public Sphere(double r):base(r)
{ }
public override double Area() //【【【【重写虚基类的方法】】】
{
return Math.PI * radius * radius*4;
}
}
public class Cylinder : Circle
{
protected double height;
public Cylinder(double r,double h):base(r)
{
height = h >= 0 ? h : 0;
}
public override double Area() //重写虚基类的方法
{
return Math.PI * radius * radius * 2+2*Math.PI*radius*height;
}
}
}
/* 如果父类的Area没有virtual修饰,且子类没有override,则,结果输出如下: */
//圆的面积:3.14
//球的面积:3.14 //----【【如果父类子类没有相关修饰符修饰,则此处,调用的方法都会默认调用父类的Area
//圆柱的面积:3.14
//请按任意键继续. . .
/* 反之,结果输出如下: */
//圆的面积:3.14
//球的面积:12.57
//圆柱的面积:18.85
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 8继承 8.6 例题-银行账户
* 题目:创建一个继承层次,让银行表示客户的银行账户。
* 1)银行账户(父类Account)可以用其账户存款,取款
* 2)存款账户(子类SavingAccount)可以获得利息(interest);
* 其构造函数接收账户结余和利率初值,并通过公用函数Calculate
* 返回其利息值
* 3)支票账户(子类CheckingAccount)则按事物收取手续费,
* 其构造函数接收账户结余初始值和事物手续费,CheckingAccount
* 类要重定义Credit和Debit,使得事物办理成功时,从账户中扣掉
* 手续费
* 要点: 重定义父类中的继承类的方法
* 时间:2019、06、19
***************************************************/
namespace EXAMPLE8_6
{
class Program
{
static void Main(string[] args)
{
SavingAccount sa = new SavingAccount(23f, 0.2f);
Console.WriteLine("sa的本金:{0}", sa.Balance); //打印账户sa的存款金额
sa.Credit(34);//存34元
Console.WriteLine("sa的剩余金额:{0}", sa.Balance); //打印账户sa的存款金额
Console.WriteLine("sa的利息:{0}", sa.CalculateInterest());
CheckingAccount ca = new CheckingAccount(15.5f,0.3f);//手续费固定0.3元每笔取款操作
Console.WriteLine("ca的本金:{0}", ca.Balance);
ca.Debit(5f);
Console.WriteLine("ca的剩余金额:{0}", ca.Balance);
}
}
public class Account
{
private float balance;//初始结余-本金private修饰,继承后,派生类不可访问该字段
public float Balance //public修饰,继承后,派生类可通过属性访问该字段
{
get {
return balance;
}
}
public Account()
{
balance = 0;
}
public Account(float b)
{
balance = b > 0 ? b : 0;
}
public void Credit(float m) //存款
{
balance += m;
}
public Boolean Debit(float m) //取款
{
if (balance >= m)
{
balance -= m;
return true;
}
else
return false;
}
}
public class SavingAccount : Account
{
private float interest; //存款利率
public SavingAccount(float b,float i):base(b)
{
interest = i;
}
public float CalculateInterest()
{
return interest * Balance;//父类的balance字段是private型的,则
//要通过public型的属性Balance来访问字段balance
}
}
public class CheckingAccount : Account
{
private float fee;
public CheckingAccount(float b,float f):base(b)
{
fee = f;
}
public new void Debit(float m) //【【【【重定义父类中的继承来的方法】】】
{ //注意区别于父类的public Boolean Debit(float m)
if (base.Debit(m))
{
base.Debit(fee);//可能余额不足以扣除手续费,暂且忽略
}
}
}
}
//sa的本金:23
//sa的剩余金额:57
//sa的利息:11.4
//ca的本金:15.5
//ca的剩余金额:10.2
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 8继承 8.5 例题-包裹投递
* 要点:快递行业投递包裹,一般按照不同紧急程度收取不同费用
* 比如,三日达,次日达,当日达
* 1)创建一个继承层次来表示不同类型的包裹,将package类
* 作为基类,将ThreeDayPackage类和OvernightPackage类作为
* 他的派生类。基类Package包含发件人和收件人的姓名,地址,
* 及包裹重量(单位:克),以及投递包裹费用(单位:克/元),
* 这些变量为protected
* 2)Package类包含必要的构件函数CalculateCost(),用于计
* 算包裹的基本费用,公式:基本费用=重量*投递标准费用单价;
* 3)ThreeDayPackage和OvernightPackage在标准基本费用基础
* 上,增加加急费用(重量*额外费用单价)
* 题目:
*
* 时间:2019、06、19
***************************************************/
namespace EXAMPLE8_5
{
class Program
{
static void Main(string[] args)
{
ThreeDayPackage tp = new ThreeDayPackage("Sender", "Receiver", "中国深圳宝安区", 1500m, 0.2m, 0.3m);//decimal的数据类型一定要带后缀m,显示指明
Console.WriteLine("tp's cost is: {0}", tp.CalculateCost());
}
}
public class Package
{
protected string SendName { get; set; }
protected string RecvName { get; set; }
protected string AddrName { get; set; }
protected decimal Weight;
protected decimal Fee;
protected decimal weight
{
get {
return Weight;
}
set {
Weight = value < 0 ? 0 : value;
}
}
protected decimal fee
{
get
{
return Fee;
}
set
{
Fee = value < 0 ? 0 : value;
}
}
public Package(string sn, string rn, string adr, decimal w, decimal f)
{
SendName = sn;
RecvName = rn;
AddrName = adr;
fee = f;
weight = w;
}
protected decimal CalculateCost()
{
return fee * weight;
}
}
public class ThreeDayPackage : Package
{
protected decimal ExFee;
protected decimal exfee
{
get
{
return ExFee;
}
set
{
ExFee = value < 0 ? 0 : value;
}
}
public ThreeDayPackage(string sn, string rn, string adr, decimal w, decimal f,decimal exf):base(sn,rn,adr,w,f)
{
exfee = exf;
}
public decimal CalculateCost() //子类的方法名可以和父类的方法命名相同,该命名将在此隐藏父类的方法
{
return exfee * weight + base.CalculateCost(); //此处要显示指明调用父类的方法CalculateCost(),而不是自己的
}
}
}
//tp's cost is: 750.0
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 8继承 8.3 例题-点和圆
* 要点:
* 1)
* 题目: 创建一个点类,并从点类继承,创建一个圆类,点是圆心;
* 添加半径,计算面积
* 时间:2019、06、17
***************************************************/
namespace EXAMPLE8_4
{
class Program
{
static void Main(string[] args)
{
Circle c1 = new Circle(2,3,4);
Console.WriteLine("子类对象调用父类继承来的show:");
c1.Show();
Console.WriteLine();
Console.WriteLine("子类对象调用自己的方法show2:");
c1.Show2();
Console.WriteLine();
Console.WriteLine("c1的面积是:{0:0.00}",c1.Area());
Circle c2 = new Circle();
c2.Show2();
Console.WriteLine();
}
}
public class Point
{
protected double x; //可被继承
protected double y; //可被继承
public Point()
{
x = y = 0;
}
public Point(double x1, double y1)
{
x = x1;
y = y1;
}
public void Show() //可被继承
{
Console.Write("x={0},y={1}",x,y);
}
}
public class Circle : Point //Circle继承Point的语法格式
{
protected double r;
public Circle()
{
r = 0;
}
public Circle(double x1,double y1,double r1):base(x1,y1) //派生类传递参数给基类
//public Circle(double x1,double y1,double r1):base(x1,y1) //派生类传递参数给基类
{
r = r1;
}
public double Area()
{
return Math.PI * r * r; //Math.PI即可获得圆周率π
}
public void Show2()
{
Show();//子类可以直接调用从父类继承来的函数
Console.Write(",r={0}",r);
}
}
}
//子类对象调用父类继承来的show:
//x=2,y=3
//子类对象调用自己的方法show2:
//x=2,y=3,r=4
//c1的面积是:50.27
//x=0,y=0,r=0
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 8继承 8.2 例题-龟兔赛跑
* 要点:
* 1)
* 题目: 龟兔赛跑
* 用随机数产生器建立模拟龟兔赛跑的程序
* 对手从70个方格的第一格开始赛跑,每格表示赛道上的一个可能的位置,终点线在
* 第70格处。程序每隔一秒钟打印显示各自位置,若选手跌到第一格以外,则移回第
* 一格,各个选手位置的随机性满足一下情况:
* -------------------------------------------------------------------------------
* 选手 运动类型 随机概率 运动情况
* -------------------------------------------------------------------------------
* 乌龟(Tortoise) 快走 50% 向右3格
* 跌倒 20% 向左6格
* 慢走 30% 向右1格
* 兔子(Hare) 睡觉 20% 不动
* 大跳 20% 向右9格
* 大跌 10% 向左12格
* 小跳 30% 向右1格
* 小跌 20% 向左2格
* 时间:2019、06、17
***************************************************/
namespace EXAMPLE8_3
{
class Program
{
static void Main(string[] args)
{
Run result = new Run();
result.Runing();
}
}
public class Tortoise
{
private int t=1;
private Random r = new Random();
public int GetPosition()
{
switch(r.Next(10))
{
case 0:
case 1:
case 2:
case 3:
case 4:
t += 3;
break;
case 5:
case 6:
t = t - 6 > 0 ? t - 6 : 1;
break;
case 7:
case 8:
case 9:
t++;
break;
default:
break;
}
return t;
}
}
public class Hare
{
private int t = 1;//初始化可以在构造函数中完成
private Random r; //申请内存,初始化可以在构造函数中完成
public Hare()
{
r = new Random();
}
public int GetPosition()
{
switch (r.Next(10))
{
case 0:
case 1:
break;
case 2:
case 3:
t += 9;
break;
case 4:
t = t - 12 > 0 ? t - 12 : 1;
break;
case 5:
case 6:
case 7:
t++;
break;
case 8:
case 9:
t = t - 2 > 0 ? t - 2 : 1;
break;
default:
break;
}
return t;
}
}
public class Run
{
private Tortoise T = new Tortoise();
private Hare H = new Hare();
//private int tPos; //这三者基本上,只供方法Runing()使用,所以,可以直接定义在方法中
//private int hPos; //这三者基本上,只供方法Runing()使用,所以,可以直接定义在方法中
//char[] str = new char[70]; //这三者基本上,只供方法Runing()使用,所以,可以直接定义在方法中
private void Dispaly(int tPos, int hPos) //只需要在Runing()方法内调用,故可将访问权设置为private
{
char[] str = new char[72]; //这三者基本上,只供方法runing()使用,所以,可以直接定义在方法中
for (int i = 0; i < 70; i++)
str[i] = ' ';
if (tPos == hPos && tPos<70)
{
str[tPos - 1] = 'S'; //当前位置相同
str[tPos - 0] = 'A'; //当前位置相同
str[tPos + 1] = 'M'; //当前位置相同
str[tPos + 2] = 'E'; //当前位置相同
}
else
{
if(tPos<=70)
str[tPos - 1] = 'T';
if(hPos<=70)
str[hPos - 1] = 'H';
}
if (tPos >= 70 && hPos >= 70)
str[69] = 'O';//同时越过终点
else if (tPos >= 70)
str[69] = 'T';//乌龟越过终点
else if (hPos >= 70)
str[69] = 'H';//兔子越过终点
else
str[69] = '|';//显示终点位置
Console.WriteLine(new string(str));//字符数组转字符串
}
public void Runing()
{
//int tpos; //这三者基本上,只供方法runing()使用,所以,可以直接定义在方法中
//int hpos; //这三者基本上,只供方法runing()使用,所以,可以直接定义在方法中
Console.WriteLine("龟兔赛跑开始:");
int tPos = T.GetPosition(); //这三者基本上,只供方法runing()使用,所以,可以直接定义在方法中
int hPos=H.GetPosition();
Dispaly(tPos, hPos);
while (tPos<70 && hPos<70)
{
tPos = T.GetPosition();
hPos = H.GetPosition();
Dispaly(tPos, hPos);
System.Threading.Thread.Sleep(1000); //休眠暂停1000ms
}
if (tPos >= 70 && hPos >= 70)
Console.WriteLine("竞赛平局");//同时越过终点
else if (tPos >= 70)
Console.WriteLine("乌龟获胜");//乌龟越过终点
else if (hPos >= 70)
Console.WriteLine("兔子获胜");//兔子越过终点
}
}
}
//龟兔赛跑开始:
//H T |
//H T |
// SAME |
//H T |
// H T |
// TH |
// H T |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// HT |
// T H |
//T H |
// T H |
// T H |
//T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
// T H |
//T H |
// T H |
// T H |
//T H|
// T H
//兔子获胜
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 8继承 8.2 例题-复数类
* 要点:
* 1)重载
* 2)
* 3)
* 题目: 编写复数类,可以实现两个复数的加法
*
* 时间:2019、06、17
***************************************************/
namespace EXAMPLE8_2
{
class Program
{
static void Main(string[] args)
{
Complex x1 = new Complex(1.2, 5.36);
Complex x2 = new Complex(4.1, 8);
x1.show();
x2.show();
Console.WriteLine("通过对象调用方法:");
Complex x3 = x1.Add(x2);
x3.show();
Console.WriteLine("通过类调用方法:");
Complex x4 = Complex.Add(x1, x2);
x4.show();
}
}
public class Complex
{
private double real;
private double image;
public Complex()
{
real = image = 0;
}
public Complex(double real, double image)
{
this.real = real;
this.image = image;
}
public Complex Add(Complex x) //对象的方法
{
Complex temp=new Complex();
temp.real = this.real + x.real;
temp.image = this.image + x.image;
return temp;//返回时,栈中的临时索引temp被销毁,但其申请的堆空间还不一定被销毁
}
public static Complex Add(Complex x, Complex y) //静态类的方法
{
Complex temp = new Complex();
temp.real = x.real + y.real;
temp.image = x.image + y.image;
return temp;
}
public void show()
{
Console.WriteLine("复数值为:{0}+{1}i",real,image);
}
}
}
//复数值为:1.2+5.36i
//复数值为:4.1+8i
//通过对象调用方法:
//复数值为:5.3+13.36i
//通过类调用方法:
//复数值为:5.3+13.36i
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 7构造析构 7.3 例题
* 要点:
* 1)构造函数
* 2)
* 3)
* 题目: 编写一个点类,描述平面上的2个点(double);
* 编写一个直线类,含有2个点,计算2点之间的距离
* 时间:2019、06、14
***************************************************/
namespace EXAMPLE7_3
{
class Program
{
static void Main(string[] args)
{
Line line1 = new Line();
Console.WriteLine("line1 distance is:{0}",line1.Distance());
Line line2 = new Line(1,5,2.1,8.8); //4各值,2个点的坐标
Console.WriteLine("line2 distance is:{0:0.000}", line2.Distance());//string.Format("{0:000.000}", 12.2) 输出012.200
Point p1 = new Point(1,5);
Point p2 = new Point(2.1,8.8);
Line line3 = new Line(p1,p2);
Console.WriteLine("line3 distance is:{0:0.000}", line3.Distance());
}
}
class Point
{
//private double x;
//private double y;
//public double X
//{
// set { x = value; }
// get { return x; }
//}
public double X { set; get; } /*当然上面的写法可以简化为“命名属性”的写法,采用这种方法,相当于后台系统有一个隐藏的变量x*/
public double Y { set; get; }
public Point()
{
X = Y = 0;
}
public Point(double x, double y)
{
X = x;
Y = y;
}
}
class Line
{
public Point p1;
public Point p2;
public Line() //构造初始化时,不带参构造函数,默认指定两点位置
{
p1 = new Point();
p2 = new Point();
}
public Line(double x1, double y1, double x2, double y2) //构造初始化时,直接定义2个点的坐标
{
p1 = new Point(x1,y1);
p2 = new Point(x2, y2);
}
public Line(Point p1, Point p2) //构造初始化时,直接传递已经定义的2个点
{
this.p1 = p1;
this.p2 = p2;
}
public double Distance() //求2点间的距离
{
return Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y)); //Math.Sqrt()求开方
}
}
}
//line1 distance is:0
//line2 distance is:3.956
//line3 distance is:3.956
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 7构造析构 7.2 构造析构
* 要点:
* 1)构造函数
* 2)构造函数的重载-(实现不同方式地对象初始化)
* 3)
* 题目: 设计一个Time类,存储时分秒,并以字符串的形式输出
* 时间:2019、06、14
***************************************************/
namespace EXAMPLE7_2
{
class Program
{
static void Main(string[] args)
{
Time t3 = new Time();
t3.show(1);
Time t0 = new Time(12);
t0.show(2);
Time t1 = new Time(12,24,56);
t1.show(3);
Time t2 = new Time(12, s:24);
t2.show(4);
t2.Hour = 11;
t2.show(5);
}
public class Time
{
private int hour;
private int min;
private int sec;
~Time()//析构函数,跟C++有所不同,C#中,析构函数不带修饰符
{
Console.WriteLine("执行析构函数destructor");
}
public Time()
{
Console.Write("default constructor--");
hour = min = sec = 0;
}
public Time(int h,int m=33,int s=45 )
{
Console.Write("With parameters constructor--");
this.hour = h >= 0 && h < 24 ? h : 0;
this.min = m >= 0 && m < 60 ? m : 0;
this.sec = s >= 0 && s < 60 ? s : 0;
}
public int Hour
{
get { return hour; }
set { hour = value >= 0 && value < 24 ? value : 0; }
}
public void show(int line)
{
Console.WriteLine("time{0} is {1:D2}:{2:D2}:{3:D2}", line,hour, min, sec); //{0:D2} D 十进制string.Format("{0:D3}", 2) 输出002
}
}
}
}
//default constructor--time1 is 00:00:00
//With parameters constructor--time2 is 12:33:45
//With parameters constructor--time3 is 12:24:56
//With parameters constructor--time4 is 12:33:24
//time5 is 11:33:24
//执行析构函数destructor
//执行析构函数destructor
//执行析构函数destructor
//执行析构函数destructor
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 6方法 6.8 方法的重载
* 要点:重载要求:
* 1)方法参数数目不同
* 2)参数数目相同,但类型不同
* 3) 参数数目类型都一样,当出现先后顺序不同
* 题目: 求三角形的面积
*
* 时间:2019、06、13
***************************************************/
namespace EXAMPLE6_8
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine( "Area1 is:{0}", TriangleArea(3d, 4d, 5d)); //数据后缀d,指明该数为double类型
Console.WriteLine( "Area2 is:{0}", TriangleArea(3, 4, 1.2));
Console.WriteLine( "Area3 is:{0}", TriangleArea(3, 4));
}
static double TriangleArea(double a, double b, double c) //输入三边长
{
Console.WriteLine(" ----------1------- ");
double s = (a + b + c) / 2;
return Math.Sqrt(s*(s-a)*(s-b)*(s-c));
}
static double TriangleArea(double a, double h) //输入边长及其高
{
Console.WriteLine("------2-----------");
return a * h / 2;
}
static double TriangleArea(int a,int b, double theta) //输入两边边长及其夹角的幅度
{
Console.WriteLine("--------3---------");
return a * b * Math.Sin(theta) / 2;
}
}
}
// ----------1-------
//Area1 is:6
//--------3---------
//Area2 is:5.59223451580336
//------2-----------
//Area3 is:6
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 6方法 6.7 可选参数\命名参数用法
* 要点: 1)变长参数表
* 2)获取数组第N维长度 GetLength(N)
* 题目: 使用变长参数,求若干个整数的平均值
*
* 时间:2019、06、13
***************************************************/
namespace EXAMPLE6_7_2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("均值1:{0}", Average(1));
Console.WriteLine("均值2:{0}", Average(1,2,3));
Console.WriteLine("均值3:{0}", Average(4,5));
int[] array = { 1, 2, 3, 4 };
Console.WriteLine("均值4:{0}", Average(array));//变长参数也可以这样传递参数
}
static double Average(params int[] a) //变长参数修饰符params
{
//int b = a.Length; //获取参数个数的方法1 Lengths
int b = a.GetLength(0);//获取参数个数的方法2 GetLength()
double s = 0; //GetLength(0)如果是二维数组,则获取第二维行的长度
foreach (int i in a) //GetLength(1)如果是二维数组,则获取第二维列的长度
s += i;
return s / b;
}
}
}
//均值1:1
//均值2:2
//均值3:4.5
//均值4:2.5
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 6方法 6.7 可选参数\命名参数用法
* 要点: 1)可选参数
* 2)命名参数用法
* 题目:
*
* 时间:2019、06、13
***************************************************/
namespace EXAMPLE6_7
{
class Program
{
static void Main(string[] args)
{
int a = 2;
double b = 45;
int c = 23;
char d = 'Y';
Console.WriteLine("--------1---------");
Sam(a,b,c,d);
Console.WriteLine("--------2---------");
Sam(a, b, c); //省略d,调用时,形参d使用默认值R
Console.WriteLine("--------3---------");
Sam(a, b, 20,d);
Console.WriteLine("--------4---------");
Sam(a, b, d:d); //命名参数用法,前一个d标识形参,后一个d是实参(对应值为'Y')
}
static void Sam(int a, double b, int c = 1, char d = 'R') //这里的参数c和d是可选参数
{
Console.WriteLine("a={0},b={1},c={2},d={3}",a,b,c,d);
}
}
}
//--------1---------
//a=2,b=45,c=23,d=Y
//--------2---------
//a=2,b=45,c=23,d=R
//--------3---------
//a=2,b=45,c=20,d=Y
//--------4---------
//a=2,b=45,c=1,d=Y
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 6方法 6.6 out参数
* 要点: 1)
* 2)
* 题目: 返回两个数的和与差
*
* 时间:2019、06、13
***************************************************/
namespace EXAMPLE6_6
{
class Program
{
static void Main(string[] args)
{
int x1 = 3;
int x2 = 5;
int x3 = 0;
int x4 = 0;
Console.WriteLine("------通过引用ref返回结果--------");
AddSub1(x1,x2,ref x3,ref x4);
Console.WriteLine("和为{0},差为{1}",x3,x4);
Console.WriteLine("------通过引用out返回结果--------");
AddSub2(x1, x2, out x3, out x4);
Console.WriteLine("和为{0},差为{1}", x3, x4);
}
static void AddSub1(int x1, int x2, ref int x3, ref int x4)
{
x3 = x1 + x2;
x4 = x1 - x2;
}
static void AddSub2(int x1, int x2, out int x3, out int x4)
{
x3 = x1 + x2;
x4 = x1 - x2;
}
}
}
//------通过引用ref返回结果--------
//和为8,差为-2
//------通过引用out返回结果--------
//和为8,差为-2
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 6方法 6.5例题-方法的参数传递
* 要点: 1)
* 2)
* 题目: 参数是值类型的值传递和引用传递;
* 参数是引用类型的值传递和引用传递
* 时间:2019、06、13
***************************************************/
namespace EXAMPLE6_5_1
{
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 99;
Console.WriteLine("------参数是值类型的值传递--------");
Swap(a, b);
Console.WriteLine("a={0},b={1}",a,b);
Console.WriteLine("------参数是值类型的引用传递--------");
Swap2(ref a, ref b); //注意引用传递的语法格式
Console.WriteLine("a={0},b={1}", a, b);
Console.WriteLine("------参数是引用类型的值传递--------");
int[] arry = { 1, 2, 3 };
Addone(arry); //值传递
foreach (int i in arry)
Console.WriteLine(i);
Console.WriteLine("--------------");
Addone1(arry); //值传递
foreach (int i in arry)
Console.WriteLine(i);
Console.WriteLine("------参数是引用类型的引用传递--------");
int[] arry2 = { 1, 2, 3 };
Addone2(ref arry2); //引用传递
foreach (int i in arry2)
Console.WriteLine(i);
}
static void Swap(int a, int b) //值传递
{
int temp;
temp = a;
a = b;
b = temp;
}
static void Swap2(ref int a,ref int b)//引用传递
{
int temp;
temp = a;
a = b;
b = temp;
}
static void Addone(int[] a) //传递的时候,内存标记是一个拷贝到a的过程,形参是实参的一个拷贝副本,但都指向同一段内存空间
{
for (int i = 0; i < a.Length; i++) //改变形参指向内存空间的值,即是改变实参指向内存空间的值
{
a[i]++;
}
//foreach (int k in a)
// a[k]++; //用法错误
}
static void Addone1(int[] a) //传递的时候,内存标记是一个拷贝到a的过程,形参是实参的一个拷贝副本
{
a = new int[4] { 12, 13, 14, 15 }; //由于形参a重新指向另一段内存空间,那么后面的操作(改变形参指向空间的值),
for (int i = 0; i < a.Length; i++) //并不会影响实参指向空间的结果
{
a[i]++;
}
}
static void Addone2(ref int[] a) //传递的时候,内存标记是一个引用到a的过程
{
a = new int[4] { 12, 13, 14, 15 }; //由于参数是引用类型的引用传递,故这里的操作将该改变调用者实参数组名指向的内存位置
for (int i = 0; i < a.Length; i++)
{
a[i]++;
}
}
}
}
//------参数是值类型的值传递--------
//a=10,b=99
//------参数是值类型的引用传递--------
//a=99,b=10
//------参数是引用类型的值传递--------
//2
//3
//4
//--------------
//2
//3
//4
//------参数是引用类型的引用传递--------
//13
//14
//15
//16
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 6方法 6.3例题-静态变量、静态方法
* 要点: 1)
* 2)
* 题目:
* 时间:2019、06、13
***************************************************/
namespace EXAMPLE6_3_1
{
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
Sample s1 = new Sample();
Console.WriteLine(Sample.count);
//s.SampleMethod();//语法错误-调用不允许
Sample.SampleMethod();//静态方法由类调用
Sample.count++; //静态变量由类访问
s.a++; //实例访问非静态成员
//s.count++;//语法错误-静态变量,不能实例访问
}
}
class Sample
{
public static int count = 0; //指定为静态的公有成员
public int a = 0; //默认非静态
public static void SampleMethod()
{
Console.WriteLine("the static SampleMethod!");
}
public Sample()
{
count++;
}
}
}
//2
//the static SampleMethod!
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 5数组 5.9例题-利用交错数组打印杨辉三角
* 要点: 1)交错数组声明、定义
* 2)
* 题目:
* 时间:2019、06、12
***************************************************/
namespace EXAMPLE5_9_
{
class Program
{
static void Main(string[] args)
{
const int N = 10;
int[][] pascal = new int[N][]; //声明有N个元素的交错数组
for(int i=0;i<N;i++)
{
pascal[i] = new int[i+1]; //设置各个元素的长度为
}
pascal[0][0] = 1;
for (int i = 1; i < N; i++) //计算出杨辉三角各个值
{
pascal[i][0] = 1;
pascal[i][i] = 1;
for (int j = 1; j < i; j++)
{
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
for (int i = 0; i < N; i++) //打印杨辉三角
{
for (int j = 0; j <= i; j++)
Console.Write("{0,5}",pascal[i][j]);
Console.WriteLine();
}
}
}
}
// 1
// 1 1
// 1 2 1
// 1 3 3 1
// 1 4 6 4 1
// 1 5 10 10 5 1
// 1 6 15 20 15 6 1
// 1 7 21 35 35 21 7 1
// 1 8 28 56 70 56 28 8 1
// 1 9 36 84 126 126 84 36 9 1
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/***************************************************
* 章节: 5数组 5.8例题-发牌与洗牌
* 要点: 1)随机数类Random的生成方法Next
* 2)类:牌
* 题目: 生成一副牌,并打乱后发牌
***************************************************/
namespace EXAMPLE5_8_1
{
class Program
{
static void Main(string[] args)
{
Card cd1=new Card();
Console.WriteLine("打乱牌序前:");
cd1.deal(); //发牌
cd1.Shuffle(); //洗牌
Console.WriteLine("打乱牌序后:");
cd1.deal();
}
}
struct CNode //单张牌的属性
{
public char suit; //花色 //默认为private访问权限
public string face; //大小
}
enum CardNum //一副牌的属性 //类似于C的宏定义
{
CARDNUMER=52, //一共52张
SUITNUMBER=4, //共4种花色
FACENUMBER=13 //每种花色13张牌
}
class Card
{
//定义扑克牌的数组
private CNode[] deck;
public Card() //构造一副牌
{
deck = new CNode[(int)CardNum.CARDNUMER]; //枚举类型在C#中使用比较特别
//Heart,Diamod,Club,Spade
char[] suit = { (char)3, (char)4, (char)5, (char)6 };//分别表示牌的四种花色-红桃、方块、梅花、黑桃
string[] face = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", };
for (int i = 0; i < (int)CardNum.CARDNUMER; i++)
{
deck[i].face = face[i % (int)CardNum.FACENUMBER];
deck[i].suit = suit[i / (int)CardNum.FACENUMBER];
}
}
public void deal() //发牌
{
Console.Write("================");
Console.Write("52张牌的发牌次序");
Console.WriteLine("================");
Console.WriteLine(" 甲\t 乙\t 丙\t 丁\t");
for(int i=0;i<(int)CardNum.CARDNUMER;i++) //枚举类型值需要强制类型转换,枚举类型使用类似于类对字段的调用
{
Console.Write("第{0,2}张:{1}{2}\t", i + 1, deck[i].suit, deck[i].face);
//if (i % 4 == 0) //将在打印4个元素前换行
if ((i+1) % 4 == 0) //将在打印4个元素后换行
Console.WriteLine();
}
}
public void Shuffle() //洗牌:方法是将一副顺序牌通过52次随机抽取,
{ //然后,将某一次的按序牌与随机指定牌进行交换
int j;
CNode temp;
Random r = new Random();
for(int i=0;i<(int)CardNum.CARDNUMER;i++)
{
j = r.Next((int)CardNum.CARDNUMER);
temp = deck[i];
deck[i] =deck[j];
deck[j] = temp;
}
}
}
}
/* 下面的打印结果中,牌的花色在控制台界面可以正常显示 */
//打乱牌序前:
//================52张牌的发牌次序================
// 甲 乙 丙 丁
//第 1张:A 第 2张:2 第 3张:3 第 4张:4
//第 5张:5 第 6张:6 第 7张:7 第 8张:8
//第 9张:9 第10张:10 第11张:J 第12张:Q
//第13张:K 第14张:A 第15张:2 第16张:3
//第17张:4 第18张:5 第19张:6 第20张:7
//第21张:8 第22张:9 第23张:10 第24张:J
//第25张:Q 第26张:K 第27张:A 第28张:2
//第29张:3 第30张:4 第31张:5 第32张:6
//第33张:7 第34张:8 第35张:9 第36张:10
//第37张:J 第38张:Q 第39张:K 第40张:A
//第41张:2 第42张:3 第43张:4 第44张:5
//第45张:6 第46张:7 第47张:8 第48张:9
//第49张:10 第50张:J 第51张:Q 第52张:K
//打乱牌序后:
//================52张牌的发牌次序================
// 甲 乙 丙 丁
//第 1张:3 第 2张:2 第 3张:2 第 4张:A
//第 5张:7 第 6张:J 第 7张:6 第 8张:8
//第 9张:K 第10张:7 第11张:8 第12张:5
//第13张:K 第14张:10 第15张:9 第16张:A
//第17张:4 第18张:4 第19张:5 第20张:10
//第21张:Q 第22张:K 第23张:6 第24张:J
//第25张:5 第26张:3 第27张:4 第28张:8
//第29张:3 第30张:3 第31张:8 第32张:9
//第33张:A 第34张:J 第35张:6 第36张:7
//第37张:10 第38张:9 第39张:2 第40张:9
//第41张:7 第42张:6 第43张:10 第44张:Q
//第45张:4 第46张:2 第47张:K 第48张:Q
//第49张:5 第50张:J 第51张:A 第52张:Q
//请按任意键继续. . .
using System;
//随机填充一维数组:
//产生100个1-99之间的随机整数,填充数组;
//数组类型是整数,大小为100
//最后输入一个整数,如果该数字在此数组中,则输出该元素位置
namespace EXAMPLE5_5_02
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[100];
Random r = new Random();
for (int i = 0; i < a.Length; i++)
{
a[i]=r.Next(1,100); //可返回1到100的之间的随机数(next方法返回整数),包括1,但不包括100
//Console.Write("{0}\t",a[i]);
}
int j = 0;
foreach (int i in a) //foreach,它可以说是一种增强型的for循环
{
Console.Write("{0,2}:{1,2}\t", j++,i); //【这里,比较特别,i表示数组元素a[i]】
}
Console.WriteLine("请输入一个整数:");
int m = Convert.ToInt32(Console.ReadLine());
for ( j = 0; j < a.Length; j++)
{
if (m == a[j])
{
Console.WriteLine("该整数在随机数中的位置是:{0}",j);
break;
}
}
if(j==a.Length)
Console.WriteLine("该整数在随机数中未找到!");
}
}
}
// 0:52 1: 6 2:23 3:95 4:92 5:40 6:41 7:94 8:34 9:76
//10:43 11:16 12:70 13:47 14:54 15:81 16: 5 17:70 18:79 19:33
//20:66 21:56 22:39 23: 9 24:85 25:50 26:73 27: 9 28:61 29:24
//30:82 31:39 32:47 33:27 34:41 35:38 36:19 37:27 38:84 39:41
//40:27 41:82 42:99 43:60 44:30 45:25 46: 2 47:99 48:40 49:16
//50:26 51:14 52:39 53:92 54: 5 55:96 56:66 57:14 58:11 59:43
//60:67 61:33 62:33 63:10 64:94 65: 4 66:69 67:44 68: 7 69:17
//70:62 71:77 72:85 73:39 74: 6 75:84 76:56 77:78 78:79 79:61
//80:49 81:73 82:68 83:45 84:98 85:68 86: 1 87:54 88:23 89:45
//90:71 91: 6 92:17 93:42 94:74 95:94 96:49 97:89 98:66 99:26
//请输入一个整数:
//27
//该整数在随机数中的位置是:33
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//例子:二维数组
//使用二维数组,完成一个3*4的矩阵加法,这两个矩阵分别是:
//1 2 3 4
//5 6 7 8
//9 10 11 12
//和
//1 4 7 11
//2 5 8 12
//3 6 9 13
namespace EXAMPLE5_2_05
{
class Program
{
static void Main(string[] args)
{
const int M = 3;
const int N = 4;
int[,] a = new int[M, N] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };//二维数组定义方法1
int[,] b = new int[,] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };//二维数组定义方法2
int[,] c = new int[M, N];
Console.WriteLine("矩阵a如下:");
for (int i = 0; i < M; i++)
{
for(int j=0;j<N;j++)
{
Console.Write("{0,4}", a[i, j]); //"{0,4}"表示第0个输出量显示位宽为4
}
Console.WriteLine();
}
Console.WriteLine("矩阵b如下:");
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
Console.Write("{0,4}", b[i, j]); //"{0,4}"表示第0个输出量显示位宽为4
}
Console.WriteLine(); //换行操作
}
Console.WriteLine("矩阵求和,结果如下:");
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
c[i, j] = a[i, j] + b[i, j];
Console.Write("{0,4}", c[i, j]);
}
Console.WriteLine(); //换行操作
}
}
}
}
//矩阵a如下:
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12
//矩阵b如下:
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12
//矩阵求和,结果如下:
// 2 4 6 8
// 10 12 14 16
// 18 20 22 24
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EXAMPLE3_2_05
{
class Program
{
static void Main(string[] args)
{
Hero heroone = new Hero();
heroone.AddLife();
heroone.Life = 90; //属性调用set
int k = heroone.Life; //属性调用get
}
}
class Hero
{
private string name; //等效为string name; 修饰符缺省值为private
private int life = 50;
public int Life //属性定义 get/set访问器
{
get //如果没有该过程,表示属性只可写
{
return life; //读
}
set //如果没有该过程,表示属性只可读
{
//life = value; //写
if (value < 0) //set过程也可加入数据合法判断代码
life = 0;
else if (value > 100)
life = 100;
else
life = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age { get;set;} //自生成,命名属性,自实现属性
public void AddLife()
{
life++;
}
public Hero() //构造函数
{
life = 0;
name = "";
}
~Hero() //析构函数
{
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EXAMPLE2_4_1
{
class Program
{
struct Student
{
public int age;
public string name;
}
enum DayOfTime
{
Morning,
Noon,
Afternoon
}
static void Main(string[] args)
{
Student s1;
s1.age = 18;
Student[] ss = new Student[100];
DayOfTime d1;
d1 = DayOfTime.Morning;
}
/* 3.1 面向对象编程:get/set访问器 */
/*--------------
* 访问修饰符 数据类型 属性名
* {
* get{
* get访问代码块
* }
* set{
* set访问代码块
* }
* }
--------------*/
//private string id = "0000";
//public string ID
//{
// get {
// return id;
// }
// set {
// id = value;
// }
//}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EXAMPLE03
{
class Program
{
static void Main(string[] args)
{
/* 变量的申明 */
Console.WriteLine("-------------EXAMPL03_变量的申明");
int x;
int y = 90; //定义变量,且赋初值
float a, b, c; //定义多个变量
const double PI = 3.1415926; //定义一个符号常量
a = 90.8F; //90.8默认为双精度浮点数,赋值给a时,需要转换,或者指明其数据类型,后缀'F',表示浮点数float
decimal employeeSalary = 0.0m; //精确十进制类型,有28个有效位 1.0 × 10−28 至 7.9 × 1028,28 位精度
//赋值
a = 89.0f;
b = 45.7F;
c = 8f;
float d = a + b + c;
c = y / 20; //求整 90/20结果为4
Console.WriteLine("y/20 = {0}", c);
bool k = a > b; //如果a大于b,k的值为true
Console.WriteLine("k = {0}", k); //打印结果 k = True
//以上申明的变量(值变量)都在栈空间,而下面的num也在栈空间,不过num是一个引用变量
int[] num = new int[100]; //这里申请的100个数据元素所在的空间不是栈内存,而是托管内存
int[] cc; //先定义一个引用变量,但为分配空间
cc = new int[40]; //然后分配空间
}
}
}
//-------------EXAMPL03_变量的申明
//y/20 = 4
//k = True
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EXAMPLE02_cout
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-------------EXAMPL02_演示输入输出:"); //C#语言里处理的数据输入,输出都是字符串
Console.WriteLine("请输入一个整数:");
string s = Console.ReadLine();
int x = Convert.ToInt32(s);
Console.WriteLine("请再输入一个整数:");
s = Console.ReadLine();
int y = Convert.ToInt32(s);
int z = x + y;
/* 下一行的整形数据z将自动以字符串的形式输出到控制台 */
Console.WriteLine("求和结果:");
Console.WriteLine(z);//Console.Write 不换行;Console.WriteLine()要换行
/* 在一行里输入多个数据 */
Console.Write("-------------EXAMPL02_在一行里输入多个数,");
Console.WriteLine("每个数用空格隔开:");
string s2 = Console.ReadLine();
string[] ss2 = s2.Split(' '); //Split(' ') 用空格切分字符串s2,得到的多个字符串存储到字符串数组ss2
double[] a = new double[ss2.Length]; //ss2.Length 获取ss2中字符串个数
double sum=0;
for (int i = 0; i < ss2.Length; i++)
{
a[i] = Convert.ToDouble(ss2[i]); //把每个数字形式表现的字符串转换为双精度浮点数,并保存到数组a
sum += a[i];
}
Console.WriteLine("以上各个数求和,值为:");
Console.WriteLine(sum); //打印求和sum值
/* 带格式输出 */
Console.WriteLine("-------------EXAMPL02_带格式输出");
Console.WriteLine("和是{0},平均数是{1}",sum,sum/ss2.Length);
}
}
}
//-------------EXAMPL02_演示输入输出:
//请输入一个整数:
//12
//请再输入一个整数:
//23
//求和结果:
//35
//-------------EXAMPL02_在一行里输入多个数,每个数用空格隔开:
//2 5 12.2
//以上各个数求和,值为:
//19.2
//-------------EXAMPL02_带格式输出
//和是19.2,平均数是6.4
//请按任意键继续. . .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EXAMPLE01
{
class Program
{
static void Main(string[] args)
{
MyClass hello = new MyClass();
hello.SayHello();
//while(true);
}
}
class MyClass
{
private int x; //字段
public void SayHello() //方法
{
Console.WriteLine("HelloWorld");
}
}
}
//HelloWorld
//请按任意键继续. . .