Advertisement
Pentium320

kolo5

Nov 30th, 2018
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.Serialization;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10. namespace ConsoleApp1
  11. {
  12.     [Serializable()]
  13.     public class MojaKlasa
  14.     {
  15.         public int A = -1;
  16.         public static int B = 0;
  17.  
  18.         public MojaKlasa() { A += 5; }
  19.         [OnSerializing()]
  20.         internal void OnSerializingMethod(StreamingContext context)
  21.         {
  22.             A += 2;
  23.             B += A;
  24.             Console.WriteLine("OnSerializingMethod: {0} {1}", A, B);
  25.         }
  26.         [OnSerialized()]
  27.         internal void OnSerializedMethod(StreamingContext context)
  28.         {
  29.             A += 3;
  30.             B -= A;
  31.             Console.WriteLine("OnSerializedMethod: {0} {1}", A, B);
  32.         }
  33.         [OnDeserializing()]
  34.         internal void OnDeserializingMethod(StreamingContext context)
  35.         {
  36.             A += 4;
  37.             B += A;
  38.             Console.WriteLine("OndDeSerializingMethod: {0} {1}", A, B);
  39.         }
  40.         [OnDeserialized()]
  41.         internal void OnDeserializedMethod(StreamingContext context)
  42.         {
  43.             A += 5;
  44.             B -= A;
  45.             Console.WriteLine("OndDeSerializedMethod: {0} {1}", A, B);
  46.         }
  47.     }
  48.     class Test
  49.     {
  50.         static void Main(string[] args)
  51.         {
  52.             MojaKlasa obj = new MojaKlasa();
  53.             BinaryFormatter formater = new BinaryFormatter();
  54.             FileStream fs = null;
  55.             try
  56.             {
  57.                 fs = new FileStream("dane.dat", FileMode.Create);
  58.                 formater.Serialize(fs, obj);
  59.             }
  60.             finally
  61.             {
  62.                 if (fs != null)
  63.                     fs.Close();
  64.             }
  65.             try
  66.             {
  67.                 fs = new FileStream("dane.dat", FileMode.Open);
  68.                 obj = (MojaKlasa)formater.Deserialize(fs);
  69.             }
  70.             finally
  71.             {
  72.                 if (fs != null)
  73.                     fs.Close();
  74.             }
  75.             Console.ReadKey();
  76.  
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement