gpt4 book ai didi

c# - 从 PHP 数组转换为 C# 字典

转载 作者:可可西里 更新时间:2023-10-31 23:06:42 24 4
gpt4 key购买 nike

我是 C# 编程的初学者。请帮我用 PHP 将此代码示例重写为 C#:

<?php
$final = array('header' => array(), 'data' => array());
$final['header'] = array('title' => 'Test', 'num' => 5, 'limit' => 5);

foreach ($results as $name => $data)
{
$final['data'][] = array('primary' =>'Primary','secondary' => 'Secondary','image' => 'test.png','onclick' => 'alert('You clicked on the Primary');');
}

header('Content-type: application/json');
echo json_encode(array($final));
?>

我试过做这样的事情,但没有成功。

Dictionary<string, string> final = new Dictionary<string, string>();
stringArray.Add("header", "data");

最佳答案

“最简单”的方法是 Dictionary<Object, Object> .由于 PHP 对数据类型非常宽松,因此 Object会给你更多的灵 active 。然后 .NET 会 box必要的值(value)。像这样的东西:

/* $final */
IDictionary<Object, Object> final = new Dictionary<Object, Object>();

/* $final["header"] */
// by keeping this separated then joining it to final, you avoid having
// to cast it every time you need to reference it since it's being stored
// as an Object
IDictionary<Object, Object> header = new Dictionary<Object, Object> {
{ "title", "Test" },
{ "num", 5 },
{ "limit", 5 }
};
// above short-hand declaration is the same as doing:
// header.Add("title", "Test");
// header.Add("num", 5);
// header.Add("limit", 5);
final.Add("header", header);

/* $final["data"] */
IList<Object> data = new List<Object>();
// not sure where `results` comes from, but I'll assume it's another type of
// IDictionary<T1,T2>
foreach (KeyValuePair<Object, Object> kvp in results)
{
data.Add(new Dictionary<Object, Object> {
{ "primary", "Primary" },
{ "secondary", "Secondary" },
{ "image", "test.png" },
{ "onclick", "alert('You clicked on the Primary');" }
});
}
final.Add("data", data);

请记住,这当然不是最优化的,但确实使它最接近您正在使用的内容。

从那里,您可以使用库(如 Newtsonsoft Json)并序列化信息。

JsonConvert.SerializeObject(final);

测试和工作:

我添加了 $results/results将两者作为相等值 (foo->Foo,bar->Bar,baz->Baz) 然后将两者序列化为 JSON 并产生相同的结果:

[{"header":{"title":"Test","num":5,"limit":5},"data":[{"primary":"Primary","secondary":"Secondary","image":"test.png","onclick":"alert('You clicked on the Primary');"},{"primary":"Primary","secondary":"Secondary","image":"test.png","onclick":"alert('You clicked on the Primary');"},{"primary":"Primary","secondary":"Secondary","image":"test.png","onclick":"alert('You clicked on the Primary');"}]}]

关于c# - 从 PHP 数组转换为 C# 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16837127/

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