如何投射ObservableCollection? [英] How to cast an ObservableCollection?

查看:90
本文介绍了如何投射ObservableCollection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好。



我有以下问题:



我有一个SaveData类应序列化ObservableCollection< personmodel>一个XML文档。

ViewModel包含此集合,而PersonModel是Model类。

我无法在SaveData类中引用Model,因为这会导致无限依赖。



当我在ViewModel中调用SerializeData()方法时,它表示它无法分配ObservableCollection< personmodel>到参数类型ObservableCollection< object> ;.

似乎逻辑...但是如何投射ObservableCollection?



代码SaveData类:

Good Morning.

I have the following problem:

I got a SaveData class which should serialize an ObservableCollection<personmodel> to a XML document.
The ViewModel contains this collection while PersonModel is Model class.
I can not reference the Model in the SaveData class because this would cause an infinite dependency.

When I invoke the SerializeData() method in the ViewModel it says that it can not assign the ObservableCollection<personmodel> to the parameter type ObservableCollection<object>.
Seems logical...but how is it possible to cast the ObservableCollection?

Code for the SaveData class:

public class SaveData
{
    private XmlSerializer serializer;
    private string saveLogPath;

    public SaveData()
    {
        serializer = new XmlSerializer(typeof(ObservableCollection<object>));
    }

    private string GetSaveLogPath()
    {
        const string saveLog = "SaveLog.xml";
        var dir = AppDomain.CurrentDomain.BaseDirectory+saveLog;
        return dir;
    }

    public void SerializeData(ObservableCollection<object> dataToSerialize)
    {
        saveLogPath = GetSaveLogPath();

        if (File.Exists(saveLogPath))
        {
            var stream = new FileStream(saveLogPath, FileMode.Open);
            serializer.Serialize(stream,dataToSerialize);
        }
        else
        {
            File.Create(saveLogPath);
            var stream = new FileStream(saveLogPath, FileMode.Open);
            serializer.Serialize(stream, dataToSerialize);
        }
    }
}





ViewModel代码:



Code for the ViewModel:

class MainWindowViewModel : INotifyPropertyChanged
{
     private ObservableCollection<PersonModel> personList;

     public MainWindowViewModel()
     {
          personList = new ObservableCollection<PersonModel>();
     }

     public void SaveData(object parameter)
        {
            serializer = new SaveData();
            serializer.SerializeData(PersonList); //Error Occurs here
        }
}





感谢任何帮助。

提前致谢。



Any help is appreciated.
Thanks in advance.

推荐答案

我在生活中遇到了同样的问题而且我搜索了很多,但我没有找到任何解决同样问题的好方法。



然后我使用 foreach 循环来投射它。

您也可以使用 foreach 循环执行相同操作。



问候,

CodeBlack
I faced the same problem in my life and I searched a lot but I didn't found any good solution for the same problem.

Then I cast it by using foreach loop.
You can also do the same using foreach loop.

Regards,
CodeBlack


这篇关于如何投射ObservableCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆