2014-12-08 67 views
0

我有一个类,我正在使用它来保存我的应用程序的各种数据。我从来没有真正实例化类,因为我希望可以从所有表单访问数据。我想序列化这个类,但它不会让我去除非我创建它的一个实例。有没有办法解决这个问题,或者更好的方法来完成我想要做的事情?序列化一个非实例化的类

这里是类:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Runtime.Serialization; 
using System.IO; 

namespace Man 
{ 
    public class ListProduct 
    { 
     public string Name; 
     public int Quantity; 
     public decimal Cost; 
     public DateTime Date; 
    } 

    public class Product 
    { 
     public string Name; 
     public bool IsCompound; 
     public decimal BuyPrice; 
     public decimal SellPrice; 
     public List<ListProduct> SubItems = new List<ListProduct>(); 
    } 

    public class ListEmployee 
    { 
     public string FirstName; 
     public string LastName; 
     public decimal Cost; 
     public decimal Hours; 
     public DateTime Date; 
    } 

    public class Employee 
    { 
     public string FirstName; 
     public string LastName; 
     public decimal Wage; 
    } 

    [Serializable()] 
    public class Items : ISerializable 
    { 
     public static List<Product> ProdList = new List<Product>(); 
     public static List<Employee> EmpList = new List<Employee>(); 

     public static List<ListProduct> BuyList = new List<ListProduct>(); 
     public static List<ListProduct> SellList = new List<ListProduct>(); 

     public static List<ListEmployee> EmpHours = new List<ListEmployee>(); 
    } 
} 

回答

2

你可能需要辛格尔顿在这里,辛格尔顿是类有私有构造。 在构造函数中启动您的类变量。

让我Items类做的码位为辛格尔顿:

public class Items 
{ 
    public readonly List<Product> ProdList; 
    public readonly List<Employee> EmpList; 
    public readonly List<ListProduct> BuyList; 
    public readonly List<ListProduct> SellList; 
    public readonly List<ListEmployee> EmpHours; 

    private static Items _Instance; 

    private Items() 
    { 
     ProdList = new List<Product>(); 
     EmpList = new List<Employee>(); 
     BuyList = new List<ListProduct>(); 
     SellList = new List<ListProduct>(); 
     EmpHours = new List<ListEmployee>(); 
    } 

    public static Items Instance 
    { 
     get { return _Instance ?? (_Instance = new Items()); } 
    } 
} 

现在Items具有财产Instance这将有Items单个对象,并通过这个属性,你可以访问所有Items类的公共属性。

Items.Instance.ProdList.Add(new Product { Name = "Name of product" }); 

在这个问题上退房Singleton模式

https://stackoverflow.com/a/2667058/2106315

0

我并不是说这是做的一个很好的方式,但在这种情况下,我总是创建一个对象,我和所有分享表格。在你的例子中,这将是类'项目'。创建此对象的一个​​实例(例如应用程序启动时),然后在打开它们时将此对象传递给所有窗体。

这是迄今为止在应用程序中拥有一些持久性的最简单方法。

0

我不知道在IDE中是否有这样的方法,但在Xamarin中,当为移动设备编程时,可以通过某个名称注册一个类。使用

using System; 

namespace myApplication 

[Register ("AppDelegate")] 
public partial class AppDelegate 
{ 
} 

您可以在程序中注册该类,以便您可以在任何地方调用该类中的属性和方法,而无需实例化该类。