⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class1.cs

📁 150个经典的入门学习程序源代码
💻 CS
字号:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Example080_基本序列化
{
	[Serializable]
	public class MyObject 
	{
		public int n1 = 0;
		public int n2 = 0;
		public String str = null;
	}
	/// <summary>
	/// Class1 的摘要说明。
	/// </summary>
	class Class1
	{
		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			//
			// TODO: 在此处添加代码以启动应用程序
			//
			Read();
			Write();
		}

		static void Read()
		{
			MyObject obj = new MyObject();
			obj.n1 = 1;
			obj.n2 = 24;
			obj.str = "Some String";
			IFormatter formatter = new BinaryFormatter();
			Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
			formatter.Serialize(stream, obj);
			stream.Close();
		}

		static void Write()
		{
			IFormatter formatter = new BinaryFormatter();
			Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
			MyObject obj = (MyObject) formatter.Deserialize(stream);
			stream.Close();

			// Here's the proof
			Console.WriteLine("n1: {0}", obj.n1);
			Console.WriteLine("n2: {0}", obj.n2);
			Console.WriteLine("str: {0}", obj.str);
			Console.Read();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -