将项添加到字符串和List <bool>()</bool>的字典中

时间:2014-03-19 09:38:04

标签: c#

我在尝试将一组键添加到字符串字典和bool列表时遇到问题,以下是我的代码:

    private Dictionary<string, List<bool>> _properties = new Dictionary<string, List<bool>>();

private void Getconfiguration(PropertyInfo[] properties, object vCapabilities, object fCapabilities, object mCapabilities, List<string> list, string capabilityPath)
        {
            var propertyValue = new List<bool>();

        foreach (var propertyInfo in properties)
        {
            var vValue = propertyInfo.GetValue(vCapabilities, null);
            var fValue = propertyInfo.GetValue(fCapabilities, null);
            var mValue = propertyInfo.GetValue(mCapabilities, null);

            var type = GetMemberType(propertyInfo);

            if (type != typeof(bool))
            {
                GetPropertiesForMembers(propertyInfo.PropertyType.GetProperties(), vValue, fValue, mValue, list, Path);
            }

            propertyValue.Add(vValue.ToBool());
            propertyValue.Add(fValue.ToBool());
            propertyValue.Add(mValue.ToBool());

            _properties.Add(propertyInfo.Name, propertyValue);
        }
        var test = _properties;
    }

我在价值测试中获得的是一组名称,但propertyValue中的数字等于键数* 3(键时间3)
是否有一种删除重复的方法这样每个Key只有三个值?
例如,如果我有5个键,则每个键的propertyValue将为15而不是3个。

由于

2 个答案:

答案 0 :(得分:1)

每次迭代都应在foreach中创建propertyValue的新实例! 这应该有效:

private Dictionary<string, List<bool>> _properties = new Dictionary<string, List<bool>>();

private void Getconfiguration(PropertyInfo[] properties, object vCapabilities, object fCapabilities, object mCapabilities, List<string> list, string capabilityPath)
        {          
           foreach (var propertyInfo in properties)
           {
            var propertyValue = new List<bool>();

            var vValue = propertyInfo.GetValue(vCapabilities, null);
            var fValue = propertyInfo.GetValue(fCapabilities, null);
            var mValue = propertyInfo.GetValue(mCapabilities, null);

            var type = GetMemberType(propertyInfo);

            if (type != typeof(bool))
            {
                GetPropertiesForMembers(propertyInfo.PropertyType.GetProperties(), vValue, fValue, mValue, list, Path);
            }

            propertyValue.Add(vValue.ToBool());
            propertyValue.Add(fValue.ToBool());
            propertyValue.Add(mValue.ToBool());

            _properties.Add(propertyInfo.Name, propertyValue);
        }
        var test = _properties;
    }

答案 1 :(得分:0)

您需要将列表初始化移动到循环中。