gpt4 book ai didi

c# - 基类与子类值的字典兼容性

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:58 25 4
gpt4 key购买 nike

我有一个对象层次结构:

MyObject
+Variable
+etc.

(所以MyObject是基类,Variable是子类之一)。

我有特定类型的字典

private ConcurrentDictionary<string, Variable> variables 
= new ConcurrentDictionary<string, Variable>();

等等

我想将所有不同的列表放在一个高级词典中,在那里我可以找到所有特定的列表:

private Dictionary<Type, ConcurrentDictionary<string, MyObject>> objects 
= new Dictionary<Type, ConcurrentDictionary<string, MyObject>>();

但我无法将特定词典添加到高级词典中:

objects.Add(typeof(Variable), variables); // DOES NOT COMPILE

有没有办法做我想做的事?我不想将变量列表定义为

private ConcurrentDictionary<string, MyObject> variables 
= new ConcurrentDictionary<string, MyObject>(); // WORKS, BUT NOT NICE TO USE

所以我想使用特定的列表来执行特定于类型的操作,但也可以通过“对象”字典对所有对象类型启用通用操作,这样我就不需要为每个子类型手动编写所有代码。

例如,我想定义这样一个方法:

    public List<Variable> GetVariables()
{
return variables.Values.ToList();
}

所以当我知道它们都是变量时,我可以使用 Variable 对象。

最佳答案

正如您在示例中看到的那样,您尝试完成的事情是不可能的,因为您正在尝试添加 ConcurrentDictionary<string, Variable> 类型的对象。和 ConcurrentDictionary<string, MyObject> 类型的对象以强类型作为 ConcurrentDictionary<string, MyObject> 的第二个参数的字典.因此,您不能添加第一种类型的对象。就像您想添加 double 一样和 string作为 Dictionary<int, string> 的第二个参数不可能的对象。

但是有一个可行的解决方法。如果您的所有类型(MyObject, Variable 等)都来自同一个接口(interface),那么您可以这样做:

public interface MyInterface
{
}

public class MyObject:MyInterface
{
}

public class Variable:MyInterface
{
}

您可以调用此代码,类似于您想要的代码。当您检索所需的字典时,您可以将对象转换为特定类型或使用通用方法,多态性将达到其目的。

ConcurrentDictionary<string, MyInterface> myClass1Dict = new ConcurrentDictionary<string, MyInterface>();
myClass1Dict.TryAdd("one", new MyObject());
myClass1Dict.TryAdd("two", new MyObject());
ConcurrentDictionary<string, MyInterface> myClass2Dict = new ConcurrentDictionary<string, MyInterface>();
myClass1Dict.TryAdd("one", new Variable());
myClass1Dict.TryAdd("two", new Variable());
ConcurrentDictionary<Type, ConcurrentDictionary<string, MyInterface>> objectDict = new ConcurrentDictionary<Type, ConcurrentDictionary<string, MyInterface>>();
objectDict.TryAdd(Type.GetType(MyObject), myClass1Dict);
objectDict.TryAdd(Type.GetType(Variable), myClass2Dict);

关于c# - 基类与子类值的字典兼容性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15108599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com