【发布时间】:2018-11-18 07:31:00
【问题描述】:
我想在字典中添加一个鸭子类型的结构,但我收到以下错误:
参数 2:无法从 '[] options>' 转换为 'UnityEngine.Object'
这是我的代码:
public class Dynamic_Interface
{
private static Dictionary<int, Object> Interface_steps = new Dictionary<int, Object>();
Dynamic_Interface()
{
var sentences = new[]
{
new
{
identifier = 1,
text = "string explain",
options = new[]
{
new
{
next = 2,
value = "this is the first option"
},
new
{
next = 2,
value = "this is the second option"
},
new
{
next = 2,
value = "this is the third option"
},
new
{
next = 2,
value = "this is the fourth option"
},
}
},
new
{
identifier = 2,
text = "string explain second var",
options = new[]
{
new
{
next = 3,
value = "this is the second first option"
},
new
{
next = 3,
value = "this is the second second option"
},
new
{
next = 3,
value = "this is the second third option"
},
new
{
next = 3,
value = "this is the second fourth option"
}
}
},
};
foreach (var sentence_obj in sentences)
{
Interface_steps.Add(sentence_obj.identifier, sentence_obj);
}
}
}
所以最后我想要一个字典,其中包含sentences[] 中的每个对象,并且字典中的名称为identifier key。
我习惯了 javascript,这真的是我第一次使用 c#,所以很抱歉初学者的错误。但我似乎真的找不到如何让它发挥作用。
如果有不清楚的地方请告诉我,以便我澄清..
【问题讨论】:
-
创建一个可以容纳句子的类会更容易,因为鸭式打字很容易出错
-
您使用的是
UnityEngine.Object而不是System.Object,可能是因为您只导入了Unity的东西。要修复它,请在字典声明中使用System.Object或导入正确的命名空间 -
@Freggar 感谢这项工作!如果您将其写为答案,我会接受。
标签: c# dictionary unity3d duck-typing