简体   繁体   English

反射铸造

[英]Reflection casting

I have an object with some fields in it and I'm using reflection to iterate the fields of that object. 我有一个带有一些字段的对象,并且正在使用反射来迭代该对象的字段。 This object is get Serialized and Deserialized. 该对象被序列化和反序列化。 I'm writing the Deserialization routine now. 我正在编写反序列化例程。 I want to iterate through the fields, grab the value from the deserializations SerializationInfo. 我想遍历字段,从反序列化SerializationInfo中获取值。 Before I started to implement Reflection, I did everything manually: 在开始实施反射之前,我手动进行了所有操作:

public SKA_MAP(SerializationInfo info, StreamingContext ctxt)
{
    //Get the values from info and assign them to the appropriate properties
    DISP_SEGS = (int)info.GetValue("DISP_SEGS", typeof(int)); 
    //other fields followed
}

and now: 现在:

public SKA_MAP(SerializationInfo info, StreamingContext ctxt)
{
    //Get the values from info and assign them to the appropriate properties
    //DISP_SEGS = (int)info.GetValue("DISP_SEGS", typeof(int));

    foreach (FieldInfo FI in this.GetType().GetFields())
    {
        FI.SetValue(this, info.GetValue(FI.Name, FI.GetType()));
    }
}

I get 我懂了

'Invalid cast from 'System.Int32' to 'System.Reflection.RtFieldInfo'.' '从'System.Int32'到'System.Reflection.RtFieldInfo'的无效转换。

OK, yes, but I put different casts in there "not shown" and nothing. 好的,是的,但是我在其中放置了不同的演员表“未显示”,什么也没有。

Try 尝试

FI.SetValue(this, info.GetValue(this));

See documentation for GetValue and SetValue 请参阅有关GetValueSetValue文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM