【问题标题】:Error while getting value of the field [duplicate]获取字段值时出错[重复]
【发布时间】:2014-12-23 23:27:51
【问题描述】:

好的,你好。我有一门课,我想在其中写通用保护程序。所以,这个类可能会被继承,我们不能只是从文件中获取一些值并将它们放入字段中。我是这样做的:

virtual public void Load(string filename) {
    if (!File.Exists(filename)) throw new FileNotFoundException("File not found.");
    FileStream fs = File.OpenRead(filename);
    BinaryFormatter bf = new BinaryFormatter();
    object loaded = bf.Deserialize(fs);
    if (!(loaded is Application)) throw new TypeLoadException("File doesn't consist any applications.");
    Application temp = loaded as Application;
    fs.Close();
    foreach (System.Reflection.MemberInfo item in temp.GetType().GetMembers()) { 
        object value = temp.GetType().GetProperty(item.Name).GetValue(temp, null);
        this.GetType().GetProperty(item.Name).SetValue(this, value, null);
    }
}

但是,在object value ... 行我遇到了一个错误:

好的,我认为这是因为我没有指定任何类型(但 object?...)
所以,我试着这样做:

foreach (System.Reflection.MemberInfo item in temp.GetType().GetMembers()) { 
    Type varType = item.GetType();
    object value = temp.GetType().GetProperty(item.Name).GetValue(temp, null) as varType;
    this.GetType().GetProperty(item.Name).SetValue(this, value, null);
}

现在错误是The type or namespace 'varType' could not be found。请帮帮我!谢谢。

附言MonoDevelop,Ubuntu 14.04。

【问题讨论】:

  • 我找不到任何可能是null :(
  • GetProperty 的结果是null 如果没有提供的命名属性。

标签: c# class serialization field


【解决方案1】:

如果你想获得Properties,为什么要使用GetMembers?并非一个类的所有成员都是财产,但您会像对待他们一样对待他们。

foreach (var prop in temp.GetType().GetProperties()) { 
    object value = prop.GetValue(temp, null);
    prop.SetValue(this, value, null);
}

【讨论】:

  • 非常感谢,它成功了!
  • 好的,我加急了。 temp.GetType().GetProperties() 返回空列表,但我的班级有 3 个属性。
  • 谢谢,我用了GetFields(),现在可以了:D
猜你喜欢
  • 2021-08-08
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2017-01-16
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多