c#向类发送对象
本文关键字:对象 | 更新日期: 2023-09-27 18:04:53
我正在编写一个既序列化又反序列化对象的类。我希望能够将这个类用于我传递给它的任何对象。
如何将对象传递给类?我需要能够访问我正在发送它的实例的类字段,并且我还需要访问类的定义,以便将文本反序列化回对象。
。
//mainpage.cs code
private void sendObjectToSerialize()
{
var db = new DatabaseHandler();
var myCar = new Car();
myCar.Make = "Chevy";
string ObjectString = db.SerializeObject(myCar);
}
private void SendStringToBeDeserialized()
{
String myString = "SomeSerializeString" //this string would have been serialized using above Obect myCar
var db = new DatabaseHandler();
var myCar = new Car();
var myCar = db.DeserializeStringToObject(String,myCar);
}
//Database Handler Code
public string SerializeObject(Object myObject)
{
var myNewObject = new myObject();//doesn't work - error myObject used as a variable not a type
//...serialize the object passed to this function
}
public Object DeserializeStringToObject(String ObjectString ,Object myObject)
{
var myNewObject = new myObject;//error myObject used as a variable not a type
//convert string to Object of type myObject...
return mynewObject;
}
下面是我的序列化器类代码:
// serializer.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace QMC1.Handlers
{
public class Serializer
{
返回一个字符串,可以保存到数据库或文件中。目前,它似乎只适用于单个对象,而不是ObservableCollection<Object>
public String ConvertObjectToJSONString<myObjectType>(myObjectType myObject)
{
string content = String.Empty;
var js = new DataContractJsonSerializer(typeof(myObjectType));
var ms = new MemoryStream();
js.WriteObject(ms, myObject);
ms.Position = 0;
var reader = new StreamReader(ms);
content = reader.ReadToEnd();
return content;
}
这将接受用上述代码创建的字符串,并再次将其作为功能齐全的Object
返回给调用者。它只会转换回原始对象类型。目前,它似乎只适用于单个对象,而不是ObservableCollection<Object>
。
public myObjectType ConvertStringToObject<myObjectType>(string CarObjectString, string myObjectName)
{
myObjectType myObject = (myObjectType)Activator.CreateInstance(Type.GetType(myObjectName));
var js = new DataContractJsonSerializer(typeof(myObjectType));
byte[] byteArray = Encoding.UTF8.GetBytes(CarObjectString);
var ms = new MemoryStream(byteArray);
myObject = (myObjectType)js.ReadObject(ms);
return myObject;
}
}
}
从任何文件调用代码-以汽车模型为例。(本例中车型参数不重要)
Serializer ser = new Serializer();
将Object转换为JSON字符串
myCarString = ser.ConvertObjectToJSONString<Car>(myCar).ToString();
将字符串保存到数据库或文件。
从数据库或文件中拉出您的字符串并将其值分配给myCarString
。将字符串转换为对象。
myCar = ser.ConvertStringToObject<Car>(myCarString, "NameSpace.Car");
使用新对象