2014-12-08 6 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()); } 
    } 
} 

지금 ItemsItems의 단일 개체가되며,이 속성에 의해 당신이 클래스 Items의 공공의 모든 속성에 액세스 할 수 있습니다 재산 Instance 있습니다. 이 질문에

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

체크 아웃 싱글 톤 패턴을

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

0

나는이 그것을하는 좋은 방법입니다 말하는 게 아니에요,하지만이 경우에 나는 항상 내가 모두와 함께 공유하는 하나 개의 객체를 생성 양식. 귀하의 예제에서 그것은 'Items'클래스가 될 것입니다. 이 객체의 인스턴스를 생성하고 (예 : 응용 프로그램이 시작될 때)이 객체를 열 때이 객체를 모든 양식에 전달합니다.

이것은 응용 프로그램에서 지속성을 유지하는 가장 쉬운 방법입니다.

0

IDE에이 방법이 있는지 모르겠지만 Xamarin에서는 모바일 장치 용 프로그래밍시 특정 이름으로 클래스를 등록 할 수 있습니다.

using System; 

namespace myApplication 

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

프로그램을 통해 클래스를 등록 할 수 있으므로 클래스를 인스턴스화하지 않고도 클래스 내에서 속성과 메서드를 호출 할 수 있습니다.

관련 문제