>  기사  >  백엔드 개발  >  C# 개체 직렬화

C# 개체 직렬화

PHPz
PHPz원래의
2024-09-03 15:05:54605검색

객체를 시퀀스나 바이트 스트림으로 변환하는 데 사용되는 프로세스를 직렬화라고 합니다. 객체를 데이터베이스, 파일 또는 메모리로 전송하기 위해 직렬화를 사용합니다. 필요한 경우 개체를 정확하게 재생성하거나 복구하기 위해 직렬화는 개체의 상태를 저장하므로 중요한 역할을 합니다. 이 설명을 통해 우리는 웹 서비스를 사용하면 한 도메인에서 다른 도메인으로 개체를 간단히 전송함으로써 개체를 원격 위치로 전송할 수 있음을 의미했습니다. 직렬화의 역과정은 직렬화된 바이트 시퀀스를 객체로 변환하는 과정이므로 역직렬화라고 합니다.

C# 개체 직렬화 구문:

C#에서 객체 직렬화를 위해 [Serialized]라는 속성이 있습니다. 속성이 정당한 방식으로 언급되지 않으면 런타임 시 SerializedException이 발생합니다.

다음은 구문입니다.

public static void SomeData()
{
string aoo = "Heyoo! Thank you for visiting us....";
FileStream boo = new FileStream(@"D:\EduCBA.txt", FileMode.Create,FileAccess.Write, FileShare.None);
BinaryFormatter coo = new BinaryFormatter();
coo.Serialize(boo, aoo);
boo.Close();
}

C# 객체 역직렬화 구문:

다음은 구문입니다.

public static void AnotherData()
{
FileStream boo = new FileStream(@"D:\EduCBA.txt", FileMode.Open,FileAccess.Read, FileShare.Read);
BinaryFormatter doo = new BinaryFormatter();
string eoo = "";
eoo = (string)doo.Deserialize(boo);
boo.Close();
Console.WriteLine("EduCBA’s-se-ria-li-za-tion-&-de-se-ria-li-za-tion-in-C#-exam-ple");
Console.WriteLine("\n");
Console.WriteLine(eoo);
}

예제를 사용한 C# 객체 직렬화

C# 객체 직렬화의 예를 살펴보겠습니다.

예시 #1

아래 코드에서는 EduCBA 클래스를 직렬화해야 하므로 [직렬화 가능]을 사용했습니다. 코드 실행 후 오류가 발생하지 않도록 하려면 이 속성을 언급해야 합니다. 직렬화하려는 클래스의 속성을 언급한 후 문자열 "CourseName1", 정수 값 "CoursePrice1", 문자열 "CourseName2" 및 정수 "CoursePrice2"라는 클래스의 네 가지 속성을 설명했습니다. 값. “E:EDUCBA.txt” 파일을 읽기 전용 모드로 열려면 hello 개체가 “hello” 개체로 생성되고 마지막에는 앞서 언급한 속성을 사용하여 “yum”이 표시됩니다.

코드:

using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace Careerplan
{
[Serializable]
class EduCBA
{
public String CourseName1;
public int CoursePrice1;
public String CourseName2;
public int CoursePrice2;
static void Main(string[] rahul)
{
EduCBA yum = new EduCBA();
yum.CourseName1 = "C# Training";
yum.CoursePrice1 = 25900;
yum.CourseName2 = "C++ Training";
yum.CoursePrice2 = 28490;
IFormatter formatter = new BinaryFormatter();
Stream hello = new FileStream(@"E:\EDUCBA.txt",FileMode.Create,FileAccess.Write, FileShare.None);
formatter.Serialize(hello, yum);
hello.Close();
hello = new FileStream(@"E:\EDUCBA.txt",FileMode.Open,FileAccess.Read, FileShare.Read);
hello.Close();
Console.WriteLine(yum.CourseName1);
Console.WriteLine(yum.CoursePrice1);
Console.WriteLine(yum.CourseName2);
Console.WriteLine(yum.CoursePrice2);
Console.ReadKey();
}
}
}

출력:

C# 개체 직렬화

예시 #2

아래 코드에서는 CBA 클래스를 직렬화해야 하므로 [직렬화 가능]을 사용했습니다. 코드 실행 후 오류가 발생하지 않도록 하려면 이 속성을 언급해야 합니다. 직렬화하려는 클래스의 속성을 언급한 후 정수 값인 "student_ID1", 문자열인 "student_name1", 이중 값인 "CGPA1"이라는 클래스의 9가지 속성을 설명했습니다. 소수점 및 유사하게 "student_ID2"는 정수 값이고 "student_name2"는 문자열이고 "CGPA2"는 double 값이고 "student_ID3" 값은 정수이고 "student_name3"은 문자열이고 "CGPA3"은 double 값입니다. 읽기 전용 모드에서 “E:EDUCBA.txt” 파일을 열려면 hello 개체가 “learn” 개체로 생성되고 결국 앞서 언급한 속성을 사용하여 다른 행에 “ID”가 표시됩니다. 데이터가 실제로 무엇을 나타내는지 언급하는 텍스트입니다.

코드:

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace StudentData
{
[Serializable]
class CBA
{
public int student_ID1;
public String student_name1;
public double CGPA1;
public int student_ID2;
public String student_name2;
public double CGPA2;
public int student_ID3;
public String student_name3;
public double CGPA3;
static void Main(string[] annie)
{
CBA ID = new CBA();
ID.student_ID1 = 15023456;
ID.student_name1 = "Rahul Kashyap";
ID.CGPA1 = 9.5;
ID.student_ID2 = 18023950;
ID.student_name2 = "Ankush Rajput";
ID.CGPA2 = 8.7;
ID.student_ID3 = 19084653;
ID.student_name3 = "Aadarsh Rajput";
ID.CGPA3 = 7.5;
IFormatter eduCBA = new BinaryFormatter();
Stream learn = new FileStream(@"E:\EDUCBA.txt",FileMode.Create,FileAccess.Write, FileShare.None);
eduCBA.Serialize(learn, ID);
learn.Close();
learn = new FileStream(@"E:\EDUCBA.txt",FileMode.Open,FileAccess.Read, FileShare.Read);
learn.Close();
Console.Write("\n");
Console.Write("Welcome! Desired data is below");
Console.Write("\n");
Console.Write("\n");
Console.Write("::TABLE::");
Console.Write("\n");
Console.Write("\n");
Console.Write("::ROW1::");
Console.WriteLine("Student_ID: {0}", ID.student_ID1);
Console.Write("::ROW2::");
Console.WriteLine("Student_Name: {0}", ID.student_name1);
Console.Write("::ROW3::");
Console.WriteLine("CGPA Scored: {0}", ID.CGPA1);
Console.Write("\n");
Console.Write("\n");
Console.Write("::ROW1::");
Console.WriteLine("Student_ID: {0}", ID.student_ID2);
Console.Write("::ROW2::");
Console.WriteLine("Student_Name: {0}", ID.student_name2);
Console.Write("::ROW3::");
Console.WriteLine("CGPA Scored: {0}", ID.CGPA2);
Console.Write("\n");
Console.Write("\n");
Console.Write("::ROW1::");
Console.WriteLine("Student_ID: {0}", ID.student_ID3);
Console.Write("::ROW2::");
Console.WriteLine("Student_Name: {0}", ID.student_name3);
Console.Write("::ROW3::");
Console.WriteLine("CGPA Scored: {0}", ID.CGPA3);
}
}
}

출력:

C# 개체 직렬화

예시 #3

아래 예에서는 객체 직렬화를 위해 먼저 스트림(FileStream) 객체 "boo"를 생성한 다음 BinaryFormatter 객체 "coo"에 대한 객체를 생성한 다음 "coo.Serialize(boo, aoo)”는 C#에서 개체 직렬화를 위한 BinaryFormatter.Serialize() 메서드입니다.

마찬가지로 개체의 역직렬화를 위해 먼저 직렬화된 출력을 읽는 데 사용되는 스트림(FileStream) 개체 "boo"를 만든 다음 BinaryFormatter 개체 "doo"에 대한 개체를 만든 다음 "를 호출했습니다. 두. Deserialize(boo)”는 C#에서 개체의 역직렬화를 위한 BinaryFormatter.Deserialize() 메서드입니다.

코드:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace EDUCBA
{
class Rahul
{
public static void SomeData()
{
string aoo = "Heyoo! Thank you for visiting us....";
FileStream boo = new FileStream(@"D:\EduCBA.txt", FileMode.Create,FileAccess.Write, FileShare.None);
BinaryFormatter coo = new BinaryFormatter();
coo.Serialize(boo, aoo);
boo.Close();
}
public static void AnotherData()
{
FileStream boo = new FileStream(@"D:\EduCBA.txt", FileMode.Open,FileAccess.Read, FileShare.Read);
BinaryFormatter doo = new BinaryFormatter();
string eoo = "";
eoo = (string)doo.Deserialize(boo);
boo.Close();
Console.WriteLine("EduCBA’s-se-ria-li-za-tion-&-de-se-ria-li-za-tion-in-C#-exam-ple");
Console.WriteLine("\n");
Console.WriteLine(eoo);
}
static void Main(string[] foo)
{
SomeData();
AnotherData();
Console.ReadLine();
}
}
}

출력:

C# 개체 직렬화

결론

위 논의를 바탕으로 C#에서 객체의 직렬화와 C#에서 동일한 객체의 역직렬화를 이해했습니다. 우리는 또한 직렬화의 중요성을 이해했습니다. 우리는 C# 직렬화 및 C# 역직렬화와 관련된 다양한 예를 두 구문과 함께 논의했습니다.

위 내용은 C# 개체 직렬화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C# 개체 유형 확인다음 기사:C# 개체 유형 확인