gpt4 book ai didi

c# - 将 Dictionary 转换为 Dictionary

转载 作者:行者123 更新时间:2023-12-04 10:14:42 25 4
gpt4 key购买 nike

我有这两个对象、一本字典和一个方法

public abstract  class Thing {}
public class Star : Thing {}

Dictionary<int, Star> dictStar;

public void listBoxAdd (Listbox listBox, Dictionary<int, Thing> thingDict){}

我想用 dictStar 调用该方法。我尝试了很多东西来转换我的字典,但我尝试过的没有任何效果。我认为这应该可行,但编译器不同意。
listBoxAdd (starList, ( Dictionary<int, Thing>) dictStar);

我收到错误 CS0030,c# 无法将星形字典转换为事物字典。

还有其他几个基于 thing 的类,我的设计要求将它们的字典传递给将在 Thing 中的字段上工作的方法。有几次我的方法只需要访问 Thing 中定义的东西。

我可以将星星转换到事物上没有问题,但是字典有问题。我尝试让该方法采用 int 和 object 字典,我可以调用,但在该方法中,我无法将对象字典转换为 Tings。

如果我在两个方法中都使用 Star Dictionaries 并调用它,则它工作正常。

我什至使用 Thing 的基类,并从它派生出 Star。

我来自 64K 大型机的旧时代,我一直在思考内存使用情况和机器周期,因此,除了不优雅之外,还要查看字典并调用每个元素,尽管它可以工作,但似乎是个坏主意。

我知道很多规则用于允许 c# 清理内存中未使用的东西,但是在调用过程中没有元素消失的危险。

最佳答案

我将解释为什么 C# 禁止它。让我们定义第二个子类 public class BlackHole : Thing {}
现在,如果您可以在尝试时将星星字典转换为事物字典var dicThings = (Dictionary<int, Thing>) dictStar
你可以稍后写 dicThings.Add(5, new BlackHole()); ,但有一个问题:运行时间 dicThings 的类型仍然是一个恒星字典......包含一个黑洞。

解决方案:

您可以将您的方法转换为具有类型约束的泛型,例如 listBoxAdd<T> .... where T : Thing
这是一个完整的示例代码:

using System;
using System.Collections.Generic;

public class Program
{
public abstract class Thing {}
public class Star : Thing {}
public class BlackHole : Thing {}

public static void DoThing (Dictionary<int, Thing> thingDict) { Console.WriteLine("DoThing"); }

public static void DoThingMagic<T> (Dictionary<int, T> thingDict) where T : Thing { Console.WriteLine("DoThingMagic"); }

public static void Main()
{
Dictionary<int, Star> dictStars = new Dictionary<int, Star>();

// line below has a compilation error to protect you from mixing stars with black holes ;)
Dictionary<int, Thing> dictThings = (Dictionary<int, Thing>) dictStars;
// it explains the method call has a compilation error too:
DoThing(dictStars);

// now this method call will compile and execute:
DoThingMagic(dictStars);
}
}

关于c# - 将 Dictionary<int, Object1> 转换为 Dictionary<int, Object2>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61130023/

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