如何使用反序列化对象? [英] How to use deserialized object?
问题描述
我正在为 Windows 8 应用程序在 C# 中序列化和反序列化一个对象.
I am serializing and deserializing an Object in C# for Windows 8 Apps.
我在将对象传递给下一个视图之前对其进行序列化,因为传递对象会抛出异常.
I am serializing my Object before passing it to the next View, because passing an object throws out exceptions.
函数 OnNavigatedTo:
function OnNavigatedTo:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string XMLString = e.Parameter.ToString();
var thisChannel = XmlDeserializeFromString(XMLString, typeof(Channel));
....}
反序列化函数:
public static Channel XmlDeserializeFromString<Channel>(string objectData)
{
return (Channel)XmlDeserializeFromString(objectData, typeof(Channel));
}
public static object XmlDeserializeFromString(string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
我想访问此对象中的数据,但类似:thisChannel.Name 不起作用.我不知道如何继续使用这个对象.
I want to access the data in this Object, but something like: thisChannel.Name doesn't work. And I don't know how that I can continue working with this Object.
推荐答案
从删除 var
开始:
//var thisChannel = XmlDeserializeFromString(XMLString, typeof(Channel));
Channel thisChannel = XmlDeserializeFromString(XMLString, typeof(Channel));
然后你至少会在错误的 object XmlDeserializeFromString()
被选择时得到一个错误.
and then you will at least get an error when the wrong object XmlDeserializeFromString()
is selected.
并确保您使用正确的:
Channel thisChannel = XmlDeserializeFromString<Channel>(XMLString);
重载应谨慎使用,一般不要与类型参数混合使用.
Overloading should be used with care and generally not mixed with Type parameters.
这篇关于如何使用反序列化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!