C#

C# 구조체 형식 및 구조체 저장하기(Serializable)

sheepone 2021. 6. 28. 14:09
반응형

구조체 형식

데이터와 관련 기능을 캡슐화할 수 있는 값 형식

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace WindowsFormsApp39
{
    public partial class Form1 : Form
    {
        [Serializable]
        public struct Point
        {
            private int x ;
            private int y ;
            private int z ;

            public Point(int x, int y, int z)
            {
                this.x = x ;
                this.y = y ;
                this.z = z ;
            }

            public int X { 
                get { return x ;  }
                set { x = value ; }
            }

            public int Y {
                get { return y ;  }
                set { y = value ; }
            }

            public int Z {
                get { return z ;  }
                set { z = value ; }
            }
        }
        
        public Form1()
        {
            InitializeComponent();

            //Save
            Point[] pSave = new Point[2];

            pSave[0].X = 0;
            pSave[0].Y = 1;
            pSave[0].Z = 2;

            pSave[1].X = 3;
            pSave[1].Y = 4;
            pSave[1].Z = 5;

            using(FileStream fs = new FileStream("Points.dat",FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs,pSave);
            }

            //Load
            Point[] pLoad ;//= new Point[2];
            using(FileStream fs = new FileStream("Points.dat",FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                pLoad = (Point[])bf.Deserialize(fs);

                for(int i=0; i<pLoad.Length; i++)
                {
                    listBox1.Items.Add("Point X = " + pLoad[i].X);
                    listBox1.Items.Add("Point Y = " + pLoad[i].Y);
                    listBox1.Items.Add("Point Z = " + pLoad[i].Z);
                }
            }
        }
    }
}

 

결과

읽어온 값 표기

 

반응형