您的位置:首页 > 其它

丶使用as关键字将对象转换为指定类型

2011-10-17 01:33 239 查看
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;
using System.IO;

namespace Example26
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
using (FileStream P_filestream = //创建文件流
new FileStream(@"D:\My Documents\Visual Studio 2008\Projects\Example26\Log.txt", FileMode.Create))
{
object P_object = P_filestream as object; //使用as关键字转换类型
if (P_object != null) //判断转换是否成功
{
MessageBox.Show("转换为 object 成功!", "提示");
}
else
{
MessageBox.Show("转换 object 失败!", "提示");
}
}
}
if (radioButton2.Checked)
{
using (FileStream P_filestream = //创建文件流
new FileStream(@"D:\My Documents\Visual Studio 2008\Projects\Example26\Log.txt", FileMode.Create))
{
object P_obj = P_filestream;
Stream P_stream = P_obj as Stream; // 使用as关键字转换类型
if (P_stream != null) //判断是否转换成功
{
MessageBox.Show("转换为 Stream 成功!", "提示");
}
else
{
MessageBox.Show("转换 Stream 失败!", "提示");
}
}
}
if (radioButton3.Checked)
{
using (FileStream P_filestream = //创建文件流
new FileStream(@"D:\My Documents\Visual Studio 2008\Projects\Example26\Log.txt", FileMode.Create))
{
object P_obj = P_filestream;
string P_str = P_obj as string; //使用as关键字转换类型
if (P_str != null) //判断是否转换成功
{
MessageBox.Show("转换为 string 成功!", "提示");
}
else
{
MessageBox.Show("转换 string 失败!", "提示");
}
}
}
}

private void Form1_Load(object sender, EventArgs e)
{

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: