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

C# 직렬화

WBOY
WBOY원래의
2024-09-03 15:30:13427검색

다음 문서에서는 C# 직렬화에 대한 개요를 제공합니다. 객체 인스턴스가 데이터 스트림으로 변환되는 과정을 직렬화(serialization)라고 하며 객체 인스턴스의 상태는 저장 위치에 지속되도록 만들어진 다양한 네트워크를 통해 전송될 수 있기 때문에 데이터 스트림으로 변환됩니다. 이는 변환된 데이터 스트림을 크로스 플랫폼에서 호환되는 형식으로 서로 다른 네트워크를 통해 전송하고, 변환된 스트림 데이터를 영구 또는 비영구 객체 상태로 저장 매체에 저장하여 동일한 복사본이 가능하도록 하는 직렬화의 장점으로 작용합니다. 나중에 만들어졌습니다.

C# 직렬화 객체의 단계

다음은 C# 직렬화 개체의 단계입니다.

  • 스트림 개체가 생성됩니다.
  • BinaryFormatter 객체가 생성됩니다.
  • Serialize( ) 메소드가 호출됩니다.

C# 직렬화 작업

  • 애플리케이션으로 작업할 때마다 동일한 데이터를 나중에 검색할 수 있도록 지속적이거나 비영구적인 매체에 데이터를 저장해야 합니다. 이는 직렬화 개념을 사용하여 달성할 수 있습니다.
  • 객체의 인스턴스를 바이트 스트림으로 변환하여 객체의 상태를 파일의 메모리나 데이터베이스로 옮기는 과정을 직렬화라고 합니다.
  • 호환되는 형식으로 네트워크를 통해 객체를 크로스 플랫폼으로 전송하려면 직렬화가 필수적입니다.
  • 직렬화를 사용하여 객체의 복제본을 생성할 수도 있습니다.
  • C#에서 직렬화를 사용하려면 프로그램에 Runtime.Serialization 네임스페이스가 포함되어 있어야 합니다.
  • [ 직렬화 가능 ] 속성은 C#에서 클래스를 직렬화 가능하게 만드는 데 사용됩니다.

[ 직렬화 가능 ] 클래스를 보여주는 예제 클래스:

코드:

[Serializable]
public class Check
{
public int code;
public string name;
}
  • 마찬가지로 클래스의 멤버를 직렬화할 수 없게 만들고 싶다면 [ NonSerialized() ] 속성을 사용할 수 있습니다.

[ NonSerialized() ] 속성을 보여주기 위해 아래 예제 클래스를 고려하세요.

코드:

[Serializable]
public class Check
{
public int code;
public string name;
[NonSerialized()]
Public double price;
}
  • C#에서는 다음과 같은 직렬화 유형을 지원합니다.

다음은 C#에서 지원하는 직렬화 유형입니다.

1. 바이너리 직렬화

  • 모든 직렬화 기술 중 가장 빠른 것은 바이너리 직렬화입니다.
  • 바이너리 직렬화를 사용하여 개체를 바이너리 스트림으로 직렬화할 수 있습니다.
  • 객체가 바이너리 직렬화를 사용하여 출력 스트림으로 직렬화되는 동안 객체의 ID는 유지됩니다.
  • 시스템. 실행 시간. Serilaization. 포맷터. 바이너리 직렬화를 사용하려면 프로그램에 바이너리 네임스페이스가 포함되어 있어야 합니다.

2. SOAP 직렬화

  • Simple Object Access Protocol은 SOAP의 약어입니다.
  • 한 애플리케이션에서 이기종 아키텍처로 구성된 다른 애플리케이션으로 객체를 전송해야 하는 경우 Simple Object Access Protocol Serialization을 사용합니다.
  • 이식성은 Simple Object Access Protocol Serialization 사용의 주요 이점입니다.
  • Simple Object Access Protocol Serialization을 사용하여 Simple Object Access Protocol 형식으로 객체를 직렬화할 수 있습니다.
  • 시스템. 실행 시간. Serilaization. 포맷터. Simple Object Access Protocol 직렬화를 사용하려면 프로그램에 Soap 네임스페이스가 포함되어야 합니다.

3. XML 직렬화

  • XML 직렬화를 사용하여 클래스 인스턴스의 공개 멤버를 XML 스트림으로 직렬화할 수 있습니다.
  • XML 직렬화 속도는 바이너리 직렬화 속도에 비해 매우 느립니다.
  • XML 직렬화를 사용하여 크로스 플랫폼 지원이 제공됩니다.
  • XML 직렬화는 텍스트 기반입니다.
  • XML 직렬화는 쉽게 읽을 수 있습니다.
  • XML 직렬화는 쉽게 편집할 수 있습니다.
  • XmlAttribute에 속성을 설정하여 XML 직렬화를 사용하여 속성을 직렬화할 수 있습니다.

XmlAttribute 사용을 보여주기 위해 아래 코드를 고려하세요.

코드:

[XmlAttribute("Name")]
public string Name
{
get
{
return Name;
}
set
{
Name = val;
}
}
  • XmlSerializer를 사용하여 XML 직렬화를 사용하여 객체를 직렬화합니다.

XmlSerializer 사용을 보여주기 위해 아래 코드를 고려하십시오.

코드:

XmlSerializer Serializer = new XmlSerializer(typeof(Prod));
using (TextWriter Writer = new StreamWriter(@"C:\Prod.xml"))
{
xmlSerializer.Serialize(Writer, prodObject);
}

4. 사용자 정의 직렬화

  • 특정 인스턴스 유형의 직렬화 및 역직렬화를 제어하기 위해 사용자 정의 직렬화를 사용합니다.
  • ISerialized 인터페이스를 구현하여 사용자 정의 직렬화를 구현할 수 있습니다.
  • GetObjectData() 메서드는 ISerialized 인터페이스에 의해 선언됩니다.

ISerialized 인터페이스를 구현하여 사용자 정의 직렬화를 시연하려면 아래 코드를 고려하세요.

코드:

[Serializable]
public class Prod : ISerializable
{
public void GetObjectData(SerializationInfo information, StreamingContext cont)
{
//Usual code
}
}

아래는 C# 직렬화의 예입니다.

직렬화 개념을 보여주는 C# 프로그램

코드:

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;
//a namespace called demo is created
namespace Demo
{
//Serializable attribute is declared
[Serializable]
//a class check is defined which will be used for serialization
class Check
{
public int identity;
public String nam;
static void Main(string[] args)
{
//an object of the check class is created to serialize it to the file Example.txt
Check ob = new Check();
ob.identity = 10;
ob.nam = "Shobha";
//a file stream is created
IFormatter format = new BinaryFormatter();
Stream stream1 = new FileStream(@"E:\Example.txt",FileMode.Create,FileAccess.Write);
//serialization of the object of the class check is done
format.Serialize(stream1, ob);
stream1.Close();
//a file stream is created
stream1 = new FileStream(@"E:\Example.txt",FileMode.Open,FileAccess.Read);
//the object of the class check is deserialized
Check ob1 = (Check)format.Deserialize(stream1);
//the data is written to the console
Console.WriteLine(ob1.identity);
Console.WriteLine(ob1.nam);
Console.ReadKey();
}
}
}

Output:

C# 직렬화

In the above program, a namespace called demo is defined. Then a Serializable attribute is defined. A class check is defined to demonstrate the concept of serialization using this class. Two properties identity and nam are defined in the class to which the values 10 and Shobha are assigned respectively. Then an object of the check class is created to serialize it to the file Example.txt. Then a formatter class is defined to convert the object of the class check to a binary stream.

Then a file stream object is created to open the file Example.txt in write mode to write the values of the properties identity and nam into it. Then serialize method is used to transfer the binary data into the text file. Finally, We use deserialize method to deserialize the contents of the text file Example.txt and the data is written to the console as shown in the output snapshot above.

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

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