-3

Ok, hello there. I have a class, in which i want to write usiversal saver. So, this class may be inherited, we can not just get some values from file and put them into fields. I did that in this way:

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);
    }
}

But, at the line object value ... i got an error:

enter image description here

Ok, i thought it happened cause i didn't specified any type (but object?...)
So, i tried to did that:

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);
}

Now error is The type or namespace 'varType' could not be found. Help me please! Thanks.

P.S. MonoDevelop, Ubuntu 14.04.

Efog
  • 1,155
  • 1
  • 15
  • 33

1 Answers1

1

If you wanna get Properties, why are you using GetMembers ? Not all members of a class are property, but you are treating them like they were.

foreach (var prop in temp.GetType().GetProperties()) { 
    object value = prop.GetValue(temp, null);
    prop.SetValue(this, value, null);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184