[英]How can I find the class of an item and later unserialize it into an object?
I am calling a method like this:我正在调用这样的方法:
await App.CDB.InsertLogItem(logStart);
await App.CDB.InsertLogItem(logViews);
LogStart and LogViews are two classes that inherit from LogBase LogStart 和 LogViews 是两个继承自 LogBase 的类
Here's the method signature:这是方法签名:
public async Task<bool> InsertLogItem(LogBase item) {
await client.CreateDocumentAsync(collectionLink, item);
}
For the case where there is no internet connectivity I am planning to store the value of item and then later replay it like this:对于没有互联网连接的情况,我计划存储 item 的价值,然后像这样重播它:
public InsertLogItem(LogBase item) {
string result = JsonConvert.SerializeObject(item);
// store result as a string and possible somehow class name in a database row
}
public async Task<bool> InsertFromDatabase {
string result = get result from database
// get result and possible class from database and convert into item
// this is the part that I am not sure how to do.
return await client.CreateDocumentAsync(collectionLink, item);
}
How can I convert result back to item here?如何在此处将结果转换回项目? I assume I need to know the class but how can I find the class?
我想我需要知道这个班级,但我怎样才能找到这个班级?
If you save both the serialized item as well as his type, you can deserialize, getting the type at run time.如果您同时保存序列化项目和他的类型,您可以反序列化,在运行时获取类型。
Code:代码:
public class BaseClass
{
public string MyProperty0 { get; set; }
}
public class TestClass : BaseClass
{
public int MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
}
public static string SerializeBaseClass<T>(T item) where T : BaseClass
{
return JsonConvert.SerializeObject(item);
}
static void Main(string[] args)
{
var item = new TestClass { MyProperty0 = "11111", MyProperty1 = 1, MyProperty2 = "1111" };
string serializedItem, serializedType;
serializedType = item.GetType().FullName;
serializedItem = SerializeBaseClass(item);
Console.WriteLine(serializedType);
Console.WriteLine(serializedItem);
var deserializedType = Type.GetType(serializedType);
var deserializedItem = JsonConvert.DeserializeObject(serializedItem, deserializedType);
Console.WriteLine(deserializedItem.GetType().FullName);
Console.ReadKey();
}
Result:结果:
Test001.Program+TestClass
{"MyProperty1":1,"MyProperty2":"1111","MyProperty0":"11111"}
Test001.Program+TestClass
As you can see, the object is deserialized to the correct type如您所见,对象被反序列化为正确的类型
You can make your method generic and constrain the open type to something that is or derives from LogBase
.您可以使您的方法通用并将开放类型限制为属于或派生自
LogBase
。 Your Document should contain everything the original class had:您的 Document 应该包含原始类的所有内容:
public async Task<bool> InsertLogItem<T>(T item) where T: LogBase
{
string result = JsonConvert.SerializeObject(item);
await client.CreateDocumentAsync(collectionLink, item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.