问题描述
我有几个具有很多字段的对象(超过40个).每个对象都略有不同.
为了编辑这些值,我使用绑定将每个对象的每个字段绑定到GUI TextBox项.这样可以使对象在内存中保持同步,并且GUI保持同步.
用户输入值后,我希望能够保存它们,因此我序列化了对象并将其保存在文件中(以XML格式).
但是,当我反序列化为新对象时,绑定会丢失.
我搜索了解决方案,但克隆解决方案始终会创建新对象.我不想创建新对象,因为我失去了绑定.
我可以通过字段复制方法编写自己的字段,但是由于字段太多,因此容易出错.
我尝试重新绑定新创建的对象(我不想这样做),但是无论如何它都无法正常工作,因为已经有与该对象类型相关联的绑定.
取消序列化到现有对象中的最佳实践方法是什么,这样我就不会丢失绑定并重新填充所有字段,而无需编写代码来手动复制每个字段?
谢谢
I have several objects that have a lot of fields (40+). Each object is slightly different.
In order to edit these values, I used binding to bind each field of each object to GUI TextBox items. This keeps the objects in memory and the GUI in sync.
Once the user has entered values I want to be able to save them so I serial the object and save it in a file (in XML format).
However when I de-serialize into a new object, the bindings are lost.
I searched for solutions but cloning solutions always create new objects. I do not want to create a new object as I lose the bindings.
I can write my own field by field copy method but it is error prone since there are so many fields.
I tried re-binding the newly created object (I did not want to have to do this) but it doesn''t work anyway because there are already bindings associated with that object type.
What is the best practices method for de-serializing into an existing object so I do not lose the bindings and repopulate all the fields without having to write code to manually copy each field?
Thanks
推荐答案
// Get class
Type myType = typeof(myClass);
// Get Properties of that class
PropertyInfo[] myClassProperties = myType.GetProperties();
MethodInfo[] myClassMethods = myType.GetMethods();
您遍历这些列表并访问所需的信息.
或者,如果您想在运行时获取类名,可以尝试:
You iterate through these lists and access the information that you need.
Or if you want to get the class name at runtime you can try:
Type myType = typeof(SomeType);//This type must exist in the assembly you want to examine
// Search in the correct assembly that contains all the classes you want
Assembly myAssempbly = Assembly.GetAssembly(myType);
Type myType = myAssempbly.GetType(desiredClass);
希望这会有所帮助
劳伦斯(Laurence)
Hope this helps
Laurence
这篇关于您如何克隆和保留绑定信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!