2015-09-22 59 views
1

我有一個類Properties和在我已經定義了一個字典是這樣的:定義詞典與prepoluated鍵C#

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

在詞典,將有3個鍵總是存在說NameNumberAge與運行期間添加更多KeyValuePairs的選項。

我想有上述的3項存在於詞典默認情況下,同時在我的代碼初始化它,這樣我就可以直接使用它像這樣:

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

我知道我能做到這一點在我的代碼中,通過將KeyValuePair添加到字典中,但我希望使用get-set直接在類中設置它以包含3個鍵。我找不到任何可以在課堂上做到的解決方案。我看着這個Creating dictionaries with predefined keys,但並不覺得滿意。

我該如何做到這一點?

+4

您是否知道[構造函數](https://msdn.microsoft.com/zh-cn/ -us /庫/ ace5hbzh.aspx)?你可能需要/需要做一些OOP閱讀 –

+0

@JamesThorpe是的,你是對的。我甚至沒有想到構造函數。我的錯。 – nitinvertigo

+0

你可以在'{ 得到; 集; } =新詞典.....' –

回答

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; } 
} 

Documentation

如果添加了這樣的事情,你可以做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

擴展方法是一個非常好的觸摸! – Slyvain

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 
      }; 
     } 
    } 
} 
+0

將會拋出一個'KeyNotFoundException' ...如何首先創建一個實例? ** yeaaaah ..搞砸了:p我的壞.. **'NullReferenceException' –

+0

你說得對,只是一秒鐘。 –

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

你可以這樣做。

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"}); 

工作提琴手code

0

我想有上述的3個鍵存在於 詞典默認情況下,而在初始化是我的代碼,以便我可以 直接使用它

你可以這樣做:

public class Properties 
    { 
     private Dictionary<string, string> extendedProperties = new Dictionary<string, string>() 
     { 
       { "Name", "" }, 
       { "Number", "" }, 
       { "Age", "" }, 
     }; 

     public IDictionary<string, string> ExtendedProperties 
     { 
      get { return extendedProperties; } 
     } 
    } 
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 
     } 
    } 
}