【问题标题】:Dictionary<string,dynamic> behaves differently when used in function where built than when used out of function, why?Dictionary<string,dynamic> 在内置函数中的行为与在函数外使用时的行为不同,为什么?
【发布时间】:2021-12-14 21:40:55
【问题描述】:

在 Windows Server 2019 上使用 VS 2019 中的调试。我正在将 Dictionary 加载到要在整个程序中使用的函数中。当我从函数 (LoadStuff) 中的字典 (dictGen) 中提取动态对象 (o) 时,它工作正常。但是,当它从函数返回时,我无法像在函数中那样从 Dictionary 中提取值并将其用作动态对象。

所以,这里是函数的简短版本:

private void LoadStuff(ref Dictionary<string, dynamic> dictGen) 
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic o = serializer.Deserialize<dynamic>("{}");
o["matchField"] = "i";
o["newField"] = "language";
dictGen.Add("sub div", o);
o = null;
o = dictGen["sub div"];
// in Immediate Window, typing o["matchField"] Displays "i" 
}

然后在调用函数中,调用LoadStuff:

Dictionary<string, dynamic> dictGen = new Dictionary<string, dynamic>();
void LoadStuff(ref dictGen);

dynamic o = dictGen["sub div"]
// In Immediate window or in use, typing o["matchField"] gives following error:

"error CS0021: Cannot apply indexing with [] to an expression of type 'object'"

我尝试使用 foreach 循环将 dictGen["sub div"] 显式转换为动态:

foreach(dynamic obj in dictGen.Values)  // using obj["matchField"]
foreach(var key in dictGen.Keys) // obj = dictGen[key]
foreach (KeyValuePair<string, dynamic> ooo in dictGen) // dynamic obj = ooo.Value;

但无论我尝试哪种方式,都会出现同样的问题。那么,在函数中使用 Dictionary 与在返回时使用 Dictionary 有什么不同呢?如何获取 obj["matchField"] 的值?

【问题讨论】:

  • 您使用的是什么类型的serializerserializer.Deserialize 在运行时实际返回的是什么类型的对象?
  • 您提供的代码不是您正在运行的代码:main 方法中的 void 会阻止编译。我已经尝试使用来自 Json.NET 和 YamlDotNet 的序列化程序来描述你所描述的内容,但我没有看到你描述的行为。请更新您的问题以提供一个最小的可重现示例。
  • 我在原帖中添加了 JavaScriptSerializer。是的,这不是整个代码。显示的内容不在 main 方法中,它确实可以编译。
  • @Velocedge 当您无法显示错误时无法帮助您 - 需要minimal reproducible example 以便有人可以重现并理解错误以帮助您。显示编译/工作正常的代码并询问为什么某些 other 代码不起作用并不是真正的 SO 工作方式。
  • MRE 工作正常,所以发布它没有多大意义。

标签: c# dictionary object dynamic


【解决方案1】:

嗯,我曾希望有人能给我一些想法,让我得到一个好的答案,但那没有发生。所以,我创建了一个普通的 ole C# 对象,并在字典中使用它而不是动态的。它在实际程序中运行良好,所以我将使用它,即使我真的很想知道为什么动态对象的行为方式如此。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多