【发布时间】: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