反射铸造

时间:2018-05-04 17:17:27

标签: c# reflection casting

我有一个包含某些字段的对象,我使用反射来迭代该对象的字段。此对象是序列化和反序列化的。我现在正在编写反序列化例程。我想迭代字段,从反序列化SerializationInfo中获取值。在我开始实现Reflection之前,我手动完成了所有操作:

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
}

现在:

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

我得到了

  

'' System.Int32'到' System.Reflection.RtFieldInfo'。'

好的,是的,但是我把不同的演员放在那里"没有显示"什么都没有。

1 个答案:

答案 0 :(得分:0)

尝试

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

请参阅GetValueSetValue

的文档