Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- name,value
- name,value
- etc.
- a,5
- Car.a = 5;
- private void AssignProperty(object obj, string propertyName, string propertyValue)
- {
- PropertyInfo property = obj.GetType().GetProperty(propertyName);
- property.SetValue(obj, Convert.ChangeType(propertyValue, property.PropertyType), null);
- }
- public class StringLinesDeserializer<T> where T : new()
- {
- public T Deserialize(string[] assignments)
- {
- T result = new T();
- foreach (string assignment in assignments)
- {
- int commaPos = assignment.IndexOf(',');
- string propertyName = assignment.Substring(0, commaPos);
- string propertyValue = assignment.Substring(commaPos + 1);
- AssignProperty(result, propertyName, propertyValue);
- }
- return result;
- }
- private void AssignProperty(object obj, string propertyName, string propertyValue)
- {
- PropertyInfo property = obj.GetType().GetProperty(propertyName);
- property.SetValue(obj, Convert.ChangeType(propertyValue, property.PropertyType), null);
- }
- }
- string[] assignments = new string[]{"a,5","b,6"};
- StringLinesDeserializer<Car> deserializer = new StringLinesDeserializer<Car>();
- Car newCar = deserializer.Deserialize(assignments);
- Car car = new Car { a = 10, name = "Golf" };
- var str = JsonConvert.SerializeObject(car);
- {"a":10,"name":"Golf"}
- Car deserializedCar = JsonConvert.DeserializeObject<Car>(str);
- var car = new Car { name = "Hellcat", a = 10 };
- var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Car));
- string carXml = null;
- using (var ms = new System.IO.MemoryStream())
- {
- serializer.Serialize(ms, car);
- carXml = System.Text.Encoding.UTF8.GetString(ms.ToArray());
- }
- <?xml version="1.0"?>
- <Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <a>10</a>
- <name>Hellcat</name>
- </Car>
- public class Car
- {
- public object a { get; set; }
- public object b { get; set; }
- }
- private Car GetCarFromFile(string strFilePath)
- {
- var lstCarFile = System.IO.File.ReadAllLines(strFilePath);
- var car = new Car();
- foreach (var c in lstCarFile)
- {
- var name = c.Split(',')[0].Trim();
- var value = c.Split(',')[1].Trim();
- car.GetType().GetProperty(name).SetValue(car, value, null);
- }
- return car;
- }
- var car = GetCarFromFile("D:/CarMembersValue.txt");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement