2013-01-31 22 views
0

我想存儲鍵值數據並能夠以有效的方式訪問它。訪問常量鍵值數據的有效方法

基本上來說:我有一個自定義對象(EquipmentObj),並且在該對象中有一個名爲「DeviceType」的屬性。在該對象的構造函數中,我傳遞一個字符串,該字符串出現在字典(EquipmentObj的局部變量)中,並且如果該字典具有該鍵,則返回一個值。

爲了儘量減少在堆上初始化25次字典(EquipmentObj實例化25-50次),我想知道是否有更有效的方法來做到這一點。

我的第一個想法是XML,但我不能添加反序列化;我不會進入這個。

我的下一個想法可能是使用靜態類。但我仍然需要定義KeyValuePair或Dictionary,並且靜態類不能有實例成員。

你會怎麼建議?

下面是我現在基本上正在做的一個示例。

class EquipmentObj 
    { 
     public EquipmentObj(string deviceType) 
     { 
      addItems(); 
      this.DeviceType = EquipmentList.ContainsKey(device_Type) ? EquipmentList[deviceType] : "Default"; 
     } 
     public string DeviceType { get; set; } 
     private Dictionary<string, string> EquipmentList = new Dictionary<string, string>(); 

     private void addItems() 
     { 
      //Add items to Dictionary 
     } 
    } 
+0

字典如何填充在第一位? – Bobson

+0

靜態類可以有靜態成員。但是你不需要那麼做,爲什麼不讓EquipmentList成爲EquipmentObj的靜態成員? –

+0

聽起來很像微型優化 - 不要浪費你的時間,在它被證明是一個問題之前,只是我的建議。 – Casperah

回答

1

一個static類不能有實例成員,但非靜態類可以有static成員。您可以製作EquipmentListaddItems()static而不更改EquipmentObj本身。

class EquipmentObj 
{ 
    public EquipmentObj(string deviceType) 
    { 
     addItems(); 
     this.DeviceType = EquipmentList.ContainsKey(device_Type) ? EquipmentList[deviceType] : "Default"; 
    } 
    public string DeviceType { get; set; } 
    private static Dictionary<string, string> EquipmentList = new Dictionary<string, string>(); 

    public static void addItems() 
    { 
     //Add items to Dictionary 
    } 
} 

你會稱其爲:

EquipmentObj.addItems(); 
0

你可以做一個經理級的處理設備類型,它不是必需的,但它確實單獨的邏輯,使accesing來自其他地區的的設備類型在你的應用程序中更容易一點。

public class EquipmentObj 
{ 
    public EquipmentObj(string deviceType) 
    { 
     this.DeviceType = EquipmentObjManager.GetDeviceType(deviceType); 
    } 
    public string DeviceType { get; set; } 
} 

public class EquipmentObjManager 
{ 
    private static Dictionary<string, string> EquipmentList = new Dictionary<string, string>(); 

    public static string GetDeviceType(string deviceType) 
    { 
     return EquipmentList.ContainsKey(deviceType) ? EquipmentList[deviceType] : "Default"; 
    } 

    public static void AddDeviceType(string deviceTypeKey, string deviceType) 
    { 
     if (!EquipmentList.ContainsKey(deviceTypeKey)) 
     { 
      EquipmentList.Add(deviceTypeKey, deviceType); 
     } 
    } 
} 

我不知道你在哪裏,你的人口詞典,但你可以叫EquipmentObjManager.AddDeviceType將項目添加到字典中。

可能不是最好的解決方案,但它可以幫助:)

+0

我正在填寫字典,只是因爲它們對商業敏感而將項目放在外面。 – Botonomous

相關問題