我有一个动态的expando对象,我无法在其中添加值。我得对象引用没有设置为对象的实例错误
public class GameSet
{
public GameAttributes Attributes { get; set; }
}
public class GameAttributes
{
public GameAttributes ()
{
dynamic expando = new ExpandoObject();
var Attribute = expando as IDictionary<string,string>;
}
public IDictionary<string,string> Attribute { get; set; }
}
var gameAttributes = new GameAttributes ();
gameAttributes.Attribute.Add(OtherDataModelAttribute.name, OtherAttributeAttribute.value); // Error comes in this line
答案 0 :(得分:3)
这一行
var Attribute = expando as IDictionary<string,string>;
在构造函数中设置一个名为Attribute
的局部变量。此变量保持未使用状态,因此一旦构造函数完成处理,对象就会被丢弃。
如果您想设置属性Attribute
,请停用var
。
更好的是,用计算属性替换Attribute
:
private readonly dynamic expando = new ExpandoObject();
IDictionary<string,object> Attribute => expando as IDictionary<string,string>;
答案 1 :(得分:1)
将动态expando对象分配给新对象
var Attribute = expando as IDictionary<string,string>;
不是班级的财产。 所以
public IDictionary<string,string> Attribute { get; set; }
尚未分配。因此它抛出异常。
尝试将代码更改为
public GameAttributes ()
{
dynamic expando = new ExpandoObject();
this.Attribute = expando as IDictionary<string,string>;
}
答案 2 :(得分:0)
如前面的答案中所述,构造函数中存在错误(使用var创建局部变量,而不是使用this.Attribute分配给成员变量)。
还有另一个错误。
ExpandoObject无法转换为
IDictionary<string,string>
相反,它可以转换为:
IDictionary<string, object>