我有一個 Dictionary<string, string> 物件,它具有以下值模板:
Key = "data[0][name]" | Value = "Test"
Key = "data[0][type]" | Value = "Type Test"
Key = "data[0][description" | Value = "描述測驗"
Key = "data[1][name]" | Value = "Test"
Key = "data[1][type]" | Value = "Type Test"
Key = "data[1][description" | 值= "描述測驗"
鍵= "
= "資料[2][型別]" | Value = "Type Test"
Key = "data[2][description" | Value = "Description Test"
我怎樣才能把這個字典決議成他們自己的具有名稱、型別、描述值的物件?
uj5u.com熱心網友回復:
首先你需要宣告你的型別別:
public class MyItem
{
public string Name {get;set;}
public string Type {get; set;}
public string Description {get;set;}
}
如果您希望推斷型別,那么在技術上可以使用 JSON 或元組結果,甚至生成器或代碼生成器/動態 IL。但這并不是 .Net 的真正作業方式。
然后你可以做這樣的事情:
public IEnumerable<MyItem> GetItems(Dictionary<string, string> items)
{
// This assume every property is always populated
int numItems = items.Count / 3; // 3 is the number of properties.
for(int i = 0;i<numItems;i )
{
yield reutrn new MyItem() {
Name = items[$"data[{i}][name]"],
Type = items[$"data[{i}][type]"],
Description = items[$"data[{i}][description]"]
};
}
}
如果您無法僅根據字典的大小推斷出您可能擁有多少個專案,則必須決議字典Keys屬性中的每個專案才能弄清楚。如果您事先不確定您的屬性是什么,情況也是如此。
uj5u.com熱心網友回復:
類似的替代方案:
using System;
using System.Linq;
using System.Collections.Generic;
namespace stack
{
class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, string>();
dict.Add("data[0][name]","Test");
dict.Add("data[0][type]","Type Test");
dict.Add("data[0][description]","Description Test");
dict.Add("data[1][name]","Test");
dict.Add("data[1][type]","Type Test");
dict.Add("data[1][description]","Description Test");
dict.Add("data[2][name]","Test");
dict.Add("data[2][type]","Type Test");
dict.Add("data[2][description]","Description Test");
int size = dict.Count/3;
foreach(var i in Enumerable.Range(0,size))
{
Func<string,string> t = (key) => dict[$"data[{i}][{key}]"];
Console.WriteLine("{0} {1} {2}", t("name"), t("type"), t("description"));
// Parse items
/*
new DataItem() {
name = t("name"),
type = t("type"),
description = t("description"),
}
*/
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/360545.html
上一篇:在Godot中使用C#異步延遲
