N47*_*1v3 3 c# dictionary object
在C#中我需要将数据保存在字典对象中,如下所示:
Dictionary<string, Dictionary<string, string>> MyDict =
new Dictionary<string, Dictionary<string, string>>();
Run Code Online (Sandbox Code Playgroud)
现在我意识到,在某些情况下,我需要一些其他(不像字典)数据作为主要字典的值.
如果我只是实例主要词典,是否有任何问题或限制.如:
Dictionary<string, object> MyDict = new Dictionary<string, object>();
Run Code Online (Sandbox Code Playgroud)
在对象字段中我可以放字符串,字典,等等..
在此先感谢,最诚挚的问候,史蒂文
是的,你的词典不再是强类型 - 在第一种方法中你可以做类似的事情:
string value = myDict["foo"]["bar"];
Run Code Online (Sandbox Code Playgroud)
在第二种方法中,这是不可能的,因为你必须先施放:
string value = ((Dictionary<string,string>)myDict["foo"])["bar"];
Run Code Online (Sandbox Code Playgroud)
听起来你的问题可以通过更好的设计方法来解决.通常,通过重新设计解决方案可以避免在同一数据结构中存储不同类型的对象的需求 - 那么为什么需要这样做呢?
编辑:
如果您只想处理null值,您可以执行以下操作:
string value = myDict["foo"] != null ? myDict["foo"]["bar"] : null;
Run Code Online (Sandbox Code Playgroud)
或者用扩展方法包装:
public static T GetValue<T>(this Dictionary<T, Dictionary<T,T>> dict,
T key, T subKey) where T: class
{
T value = dict[key] != null ? dict[key][subKey] : null;
return value;
}
string value = myDict.GetValue("foo", "bar");
Run Code Online (Sandbox Code Playgroud)
你可以这么做。从主字典中检索数据后,您必须将结果转换为适当的类型:
object obj;
If(mainDict.TryGetValue("key", out obj)) {
var dict = obj as Dictionary<string, string>>;
if (dict != null) {
// work with dict
} else {
var value = obj as MyOtherType;
....
}
}
Run Code Online (Sandbox Code Playgroud)
但请注意,这不是类型安全的;即,编译器只能部分检查代码有关 type 值的有效性object。
或者,您可以尝试更面向对象的解决方案
public abstract class MyBaseClass
{
public abstract void DoSomething();
}
public class MyDictClass : MyBaseClass
{
public readonly Dictionary<string, string> Dict = new Dictionary<string, string>();
public override void DoSomething()
{
// So something with Dict
}
}
public class MyTextClass : MyBaseClass
{
public string Text { get; set; }
public override void DoSomething()
{
// So something with Text
}
}
Run Code Online (Sandbox Code Playgroud)
然后声明你的主字典
var mainDict = new Dictionary<string, MyBaseClass>();
mainDict.Add("x", new MyDictClass());
mainDict.Add("y", new MyTextClass());
...
MyBaseClass result = mainDict[key];
result.DoSomething(); // Works for dict and text!
Run Code Online (Sandbox Code Playgroud)