c# - 将对象反序列化为自身

标签 c# .net xaml microsoft-metro

我发现了一些关于这个问题的线程,例如 thisthis但我不知道如何为我的代码实现这个。

我有这样的东西:

public sealed class Party
{
    public Party()
    {
        load();
    }
    ....
    public async void Load()
    {
       string fileName = this.Name + ".xml";
       var files = ApplicationData.Current.LocalFolder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName).GetResults();
        var file = files.FirstOrDefault(f => f.Name == fileName);
        if (file != null)
        {
            using (var stream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(fileName))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Party));
                Party data = (Party)serializer.Deserialize(stream);
                this = data;
            }
        }
    }
}

这给我带来了“无法分配给‘this’,因为它是只读的”。由于我读取了一个文件并且需要等待它,因此它必须是异步的,然后我不能将该类作为返回类型。

关于如何将其反序列化到自身的任何想法?

最佳答案

您无法分配给。它是一个对象的实例,更改它是没有意义的。

要么有一个返回 Party 的静态方法(并使用它来创建类):

public static Party Load()
{
    // ... Deserialize
    return (Party)serializer.Deserialize(stream);
}

或者使用反序列化对象将信息加载到您的类中(这会效率低下,因为它们是相同的类型):

public void Load()
{
    // ... Deserialize
    Party data = (Party)serializer.Deserialize(stream);
    this.Name = data.Name;
    this.PartyInfo = data.PartyInfo;
} 

显然,这里应该首选静态方法,并且被认为是 factory pattern .

关于c# - 将对象反序列化为自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28055274/

相关文章:

c# - 如何在 C# 中更改复选框值时计算 DataGridView 中选中的复选框?

c# - 指定的架构无效。错误 : Multiple types with the name

c# - 在 C++ 背景下迁移到 WPF 和 C# 的资源

c# - 如何使用 XML-RPC.NET 为方法定义可选参数

c# - .Net Windows Forms - 在等待异步工作时限制表单导航

c# - 使用 HttpClient 如何查看请求内容主体?

c# - 在叠加视频(VLC Winform)上绘制透明控件(文本)

c# - 使用导航时将值从另一个页面传递到 Silverlight 中的 MainPage.xaml?

c# - 命名空间 "clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"中不存在名称 ChromiumWebBrowser

c# - 应用程序调用了为不同线程编码的接口(interface) - Windows 应用商店应用程序