问题描述
我有一个类,我用来保存我的应用程序的各种数据。我从来没有实例化类,因为我想要从所有形式访问数据。我想序列化这个类,但它不会允许我,除非我创建它的一个实例。
I have a class that I'm using to hold various data for my application. I never actually instantiate the class because I want the data to be accessible from all forms. I want to serialize this class, but it won't allow me to unless I create an instance of it. Is there a way around this or maybe a better way to accomplish what I'm trying to do?
这是类:
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>();
}
}
推荐答案
可能需要Singleton这里,Singleton是有私有构造函数的类。
在构造函数中启动你的类变量。
You might required Singleton here, Singleton is class which have private constructor.Initiate your class variable in constructor.
让我做一些代码 Items
as Singleton :
Let me do bit of code for class Items
as Singleton:
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()); }
}
}
code>具有属性实例
,它将具有 Items
的单个对象,并且通过此属性,您可以访问所有项目的公共属性
。
Now Items
has property Instance
which will have single object of Items
and by this property you can access all of public properties of class Items
.
Items.Instance.ProdList.Add(new Product { Name = "Name of product" });
检查此问题中的单例模式
Check out singleton pattern in this question
这篇关于序列化一个非实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!