0

我想存储键值数据并能够以有效的方式访问它。

基本上:我有一个自定义对象(EquipmentObj),并且该对象中有一个名为“DeviceType”的属性。在对象的构造函数中,我将一个字符串传递给字典(设备对象的局部变量),如果字典有键,则返回一个值。

为了尽量减少在堆上初始化 Dictionary 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 
        }
    }
4

2 回答 2

1

static不能有实例成员,但非静态类可以有static成员。您可以在不改变自身的情况下制作EquipmentListaddItems()两者。staticEquipmentObj

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();
于 2013-01-31T22:08:21.137 回答
0

您可以创建一个 Manager 类来处理设备类型,它不是必需的,但它确实分离了逻辑并使从应用程序中的其他区域访问设备类型更容易一些。

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将项目添加到字典中。

可能不是您的最佳解决方案,但它可能会有所帮助:)

于 2013-01-31T22:13:58.593 回答