英文:
c# get multidimensional array value
问题
从以下示例代码中获取数组数据的方法:
var AllData = new Dictionary<string, object>
{
    { "TestFun", await TestFun() },
};
var TestFun = (Dictionary<string, object>)AllData["TestFun"]; // ok
string String1 = TestFun["String1"].ToString(); // ???
private static async Task<Dictionary<string, object>> TestFun()
{
    var MultiArray = new Dictionary<string, object>
    {
        { "String1", "Value1" },
    };
    return MultiArray;
}
错误信息:
System.InvalidCastException: 无法将类型为 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' 的对象强制转换为类型 'System.Collections.ArrayList'。
或
无法对类型为 'object' 的表达式应用索引。
尝试在这里获取答案,但未找到解决方法。
英文:
How to get data from array sample code below
var AllData = new Dictionary<string, object>
        {
            { "TestFun", await TestFun() },
        };
var TestFun = AllData["TestFun"] // ok
ArrayList Humidity = (ArrayList)AllData["TestFun"]; // Error
String String1= TestFun["String1"] // ???
private static async Task<Dictionary<string, object>> TestFun() { 
    var MultiArray = new  Dictionary<string, object>
        {
            { "String1", "Value1"},
        };
    return MultiArray;
}
Error
> System.InvalidCastException: 'Unable to cast object of type > 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type > 'System.Collections.ArrayList'.'
Or
> Cannot apply indexing with [] to an expression of type 'object'
Tried to get an answer here but couldn't find a solution...
答案1
得分: 2
TestFun() 返回一个 Dictionary<string,object>。
System.InvalidCastException: '无法将类型为 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' 的对象转换为类型为 'System.Collections.ArrayList' 的对象。'
异常告诉您无法将其转换为 ArrayList。您正在尝试从苹果转变为猴子。
您可以将 MultiArray 变量的类型更改为 ArrayList,或将转换类型更改为 Dictionary<string,object>。
英文:
TestFun() returns a Dictionary<string,object>.
System.InvalidCastException: 'Unable to cast object of type > 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type > 'System.Collections.ArrayList'.'
The exception tells you that it is not possible to cast/convert it to an ArrayList. You are trying to go from apples to monkeys.
You can either replace the type of the MultiArray variable to be an ArrayList or change the cast type to Dictionary<string,object>
答案2
得分: 0
字典<string, object> TestFun = (字典<string, object>)所有数据[键:"TestFun"];
字符串 String1 = (字符串) TestFun["String1"];
控制台.写入行(String1); // 值1
英文:
Dictionary<string, object> TestFun = (Dictionary<string, object>)AllData[key: "TestFun"];
string String1 = (string) TestFun["String1"];
Console.WriteLine(String1); // Value1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论