在 C# 中使用重新填充的键定义字典

问题描述 投票:0回答:6

我有一个类,

Properties
,我在其中定义了一个像这样的字典:

 public class Properties
    {
        public IDictionary<string, string> ExtendedProperties
        {
            get;
            set;
        }
    }

在字典中,始终会出现三个键,即

Name
Number
Age
,并且可以选择在运行时添加更多
KeyValuePairs

我希望在我的代码中初始化它时,默认情况下会在字典中显示上述 3 个键,以便我可以像这样直接使用它:

Properties objProps = new Properties();
objProps.ExtendedProperties["Name"] = "SomeName";

我知道我可以通过将 KeyValuePair 添加到字典中来在代码中实现此目的,但我希望使用

get-set
直接在类中设置它以包含 3 个键。我找不到任何在班级本身中做到这一点的解决方案。我研究了这个使用预定义键创建字典,但没有发现它令人满意。

我怎样才能实现这个目标?

c# dictionary
6个回答
4
投票

从 C# 6 开始,你可以执行以下操作:

using System;
using System.Collections.Generic;

public class Properties
{
    public IDictionary<string, string> ExtendedProperties { get; set; }

    public Properties(string name, string number, string age) 
    {
        this.ExtendedProperties = new Dictionary<string, string>() 
        { 
            ["Name"] = name,
            ["Number"] = number,
            ["Age"] = age
        };
    }
}

如您所见,您需要在构造函数中定义它。

还有一些您可能想使用的很酷的功能:

public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

文档

如果你添加这样的东西,你可以这样做

new Properties()["Name"]

您的代码示例:

using System;
using System.Collections.Generic;

public class Properties
{
    private IDictionary<string, string> extendedProperties;

    public string this[string key] 
    {
        get { return extendedProperties[key]; }
        set { extendedProperties[key] = value; }        
    }

    public Properties() 
    {
        this.extendedProperties = new Dictionary<string, string>() 
        { 
            ["Name"] = "something",
            ["Number"] = "something",
            ["Age"] = "something"
        };
    }
}

1
投票

像这样:

public class Properties
    {
        public IDictionary<string, string> ExtendedProperties
        {
            get;
            set;
        }

      public Properties()
      {
         this.ExtendedProperties = new Dictionary<string, string>()
         {
            { "Name", String.Empty },
            { "Number", String.Empty },
            { "Age", String.Empty },
         };

      }
    }

您可能想查看一些文档:https://msdn.microsoft.com/en-us/library/bb531208.aspx


1
投票

在构造函数中添加这 3 个条目怎么样?

using System;
using System.Collections.Generic;

namespace My.Namespace
{
    public class Properties
    {
        public IDictionary<string, string> ExtendedProperties { get; set; }

        public Properties()
        {
            ExtendedProperties = new Dictionary<string, string>
            {
                ["Name"] = String.Empty,
                ["Number"] = String.Empty,
                ["Age"] = String.Empty
            };
        }
    }
}

1
投票

你可以做到这一点。

 public class Properties
 {
     public IDictionary<string, string> ExtendedProperties
     {
         get;
         set;
     }

     public Properties(string [] fields)
     {
         ExtendedProperties = new Dictionary<string, string> ();
         foreach(var s in fields)
         {
             ExtendedProperties.Add(s,string.Empty);
         }
     }
 }

用途:

Properties p = new Properties(new [] {"Name","Number", "Age"});

工作小提琴手代码


1
投票

我会选择实施

IDictionary<string, string>
,因为它更安全,更容易使用其他键进行扩展:(接下来的长课)

class Properties : IDictionary<string, string>
{
    private Dictionary<string, string> _staticProps;
    private Dictionary<string, string> _otherProps;

    public Properties()
    {
        _staticProps = new Dictionary<string, string>
        {
            {"Name", "" },
            {"Number", "" },
            {"Age", "" }
        };
        _otherProps = new Dictionary<string, string>();
    }

    public ICollection<string> Keys
    {
        get
        {
            return (ICollection<String>)_otherProps.Keys.Concat(_staticProps.Keys);
        }
    }

    public ICollection<string> Values
    {
        get
        {
            return (ICollection<String>)_otherProps.Values.Concat(_staticProps.Values);
        }
    }

    public int Count
    {
        get
        {
            return _otherProps.Count + _staticProps.Count;
        }
    }

    public bool IsReadOnly
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    public string this[string key]
    {
        get
        {
            if (_otherProps.ContainsKey(key))
            {
                return _otherProps[key];
            }
            if(_staticProps.ContainsKey(key))
            {
                return _staticProps[key];
            }
            throw new KeyNotFoundException(key);
        }

        set
        {
            if (_otherProps.ContainsKey(key) || _staticProps.ContainsKey(key))
            {
                throw new ArgumentException("key exists: " + key);
            }
            _otherProps[key] = value;
        }
    }

    public bool ContainsKey(string key)
    {
        return _otherProps.ContainsKey(key) || _staticProps.ContainsKey(key);
    }

    public void Add(string key, string value)
    {
        _otherProps.Add(key, value);
    }

    public bool Remove(string key)
    {
        if (_staticProps.ContainsKey(key))
        {
            throw new ArgumentException("key is static, cannot be removed: " + key);
        }
        return _otherProps.Remove(key);
    }

    public bool TryGetValue(string key, out string value)
    {
        return _otherProps.TryGetValue(key, out value) || _staticProps.TryGetValue(key, out value);
    }

    public void Add(KeyValuePair<string, string> item)
    {
        if (_staticProps.ContainsKey(item.Key))
        {
            throw new ArgumentException("key exist an is static: " + item.Key);
        }
        _otherProps.Add(item.Key, item.Value);
    }

    public void Clear()
    {
        _otherProps.Clear();
        foreach (var key in _staticProps.Keys)
        {
            _staticProps[key] = string.Empty;
        }
    }

    public bool Contains(KeyValuePair<string, string> item)
    {
        return _otherProps.Contains(item) || _staticProps.Contains(item);
    }

    public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
    {           
        // define yourself how you want to handle arrayIndex between the two dictionaries
    }

    public bool Remove(KeyValuePair<string, string> item)
    {
        if (_staticProps.ContainsKey(item.Key))
        {
            throw new ArgumentException("key is static, cannot be removed: " + item.Key);
        }
        return _otherProps.Remove(item.Key);
    }

    public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
    {
        return _otherProps.Concat(_staticProps).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _otherProps.Concat(_staticProps).GetEnumerator();
    }
}

0
投票

我会将这个逻辑封装在属性本身中:

public class Properties
{
    private IDictionary<string, string> _extendedProperties;
    public IDictionary<string, string> ExtendedProperties
    {
        get
        {
            return
                _extendedProperties == null ?
                    new Dictionary<string, string>() { { "Name", "" }, { "Number", "" }, { "Age", "" } } :
                    _extendedProperties;
        }
        set 
        { 
            _extendedProperties = value; 
            //here you can also check if value misses those key to add them to _extendedProperties
        }
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.