16.类型转换[值类型和引用类型的转换]
1. 值类型
private void Form1_Load(object sender, EventArgs e)
{
int a = 6; //System.int32
long b=5; //System .int64
// b = a; //隐式转换
a = (int)b; //显示转换
// MessageBox.Show(b + "");
MessageBox.Show(a+"");
}
2. 引用类型
(1)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Fruit f = new Apple();
Apple a = (Apple)f;
MessageBox.Show(a.i+"");
}
}
class Fruit
{
}
class Apple:Fruit
{
public int i = 1;
}
(2)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Fruit f = new Apple();
if (f is Apple)
{
Apple a = (Apple)f;
MessageBox.Show(a.i+"");
}
}
}
class Fruit
{
}
class Apple:Fruit
{
public int i = 1;
}
(3)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Fruit f = new Apple();
Apple a = f as Apple ;
if (a!=null)
{
MessageBox.Show(a.i+"");
}
}
}
class Fruit
{
}
class Apple:Fruit
{
public int i = 1;
}
实例1
(第一行代码功能是所有的控件都显示在TextBox1里)