Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- namespace Reflecs;
- class Student
- {
- public string Name { get; set; }
- public int Age { get; set; }
- public string University { get; set; }
- }
- class Program
- {
- static void Main()
- {
- var student = new Student
- {
- Name = "Kendrick Lamar",
- Age = 35,
- University = "UrFU"
- };
- var serialized = Serializer.Serialize(student);
- Console.WriteLine($"Serialized: {serialized}");
- var deserialized = Serializer.DeserializeObject<Student>(serialized);
- Console.WriteLine($"Deserialized: {deserialized.Name}, {deserialized.Age}, {deserialized.University}");
- }
- }
- class Serializer
- {
- public static string Serialize(object obj)
- {
- var properties = obj.GetType().GetProperties();
- var serializedString = "";
- foreach (var property in properties)
- {
- if (property.CanRead)
- {
- var propertyName = property.Name;
- var propertyValue = property.GetValue(obj);
- var serializedProperty = $"{propertyName}:{propertyValue};";
- serializedString += serializedProperty;
- }
- }
- return serializedString;
- }
- public static T DeserializeObject<T>(string serializedString) where T : new()
- {
- var obj = new T();
- var type = typeof(T);
- var properties = type.GetProperties();
- var serializedProperties = serializedString.Split(';');
- foreach (var serializedProperty in serializedProperties)
- {
- var propertyData = serializedProperty.Split(':');
- if (propertyData.Length == 2)
- {
- var propertyName = propertyData[0];
- var propertyValue = propertyData[1];
- var property = properties.FirstOrDefault(p => p.Name == propertyName);
- if (property != null && property.CanWrite)
- {
- var propertyType = property.PropertyType;
- var convertedValue = Convert.ChangeType(propertyValue, propertyType);
- property.SetValue(obj, convertedValue);
- }
- }
- }
- return obj;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement