将数据赋值给变量时出现 NullReferenceException



在Unity3D中,我试图遍历对象上的所有组件并获取它们的变量和值。 这是不断引发异常的代码:

componentvariables = new ComponentVars[component.GetType().GetFields().Length];
int x = 0;
//Get all variables in component
foreach(FieldInfo f in component.GetType().GetFields()){
    componentvariables[x]=new ComponentVars();
    componentvariables[x].Vars.Add(f.Name,f.GetValue(component).ToString());
    x++;
}

ComponentVars 类是

public class ComponentVars{
    public Dictionary<string, string> Vars{get;set;}
}

是的,我知道它非常简单,我可以使用一系列词典,但我计划稍后添加更多词典。

不断抛出错误的部分是

componentvariables[x].Vars.Add(f.Name,f.GetValue(component).ToString());

我通常会在变量未初始化的地方看到这些,但我尝试初始化它(如上面的代码所示),但我仍然继续获得 NullRefEx。

谁能看出我在这里做错了什么?

在尝试向Vars字典添加值之前,请确保对其进行初始化:

foreach(FieldInfo f in component.GetType().GetFields()){
    componentvariables[x] = new ComponentVars();
    componentvariables[x].Vars = new Dictionary<string, string>();
    componentvariables[x].Vars.Add(f.Name, f.GetValue(component).ToString());
    x++;
}

或者更好的是,在类中初始化它:

public class ComponentVars{
    public Dictionary<string, string> Vars { get; private set; }
    public ComponentVars()
    {
        this.Vars = new Dictionary<string, string>();
    }
}

最新更新