简体   繁体   中英

Cast FieldInfo to list in C#

I have string array like this:

namespace DynamicCore
    {
        public class DynamicCode
        {
            List<Variable> variableList = new List<Variable>();
            public DynamicCode()
            {
                Variable Variable = new Variable();                    
                Variable.ID = "Variable_26545789";
                Variable.Type = 1;

                variableList.Add(Variable);

                Variable = new Variable();
                Variable.ID = "Variable_vdvd3679";
                Variable.Type = 2;

                variableList.Add(Variable);
            }
        }
    }

I compiled this array and store it to memory. I get variableList by this code:

string name = "DynamicCore.DynamicCode";
Type type = results.CompiledAssembly.GetType(name, true);
object instance = Activator.CreateInstance(type);    
FieldInfo filed = type.GetField("variableList", 
                                 BindingFlags.Instance | 
                                 BindingFlags.NonPublic);

I try to cast filed ( variableList ) to List<Variable> like this:

List<Variable> Variables = (List<Variable>)filed;

But I got this error:

Cannot convert type 'System.Reflection.FieldInfo' to 'System.Collections.Generic.List<Variable>'    

It would be very helpful if someone could explain solution for this problem.

Your variable filed is filled with metadata about your field Variable . Using this metadata you can find out in which class it is located, if it is private, etc. etc.

You want something else. You want to retrieve the value of the field use it. You need one extra step:

object theActualValue = filed.GetValue(instance);

You can use this value to cast to your list:

List<Variable> Variables = (List<Variable>)theActualValue;

My suggestion is to rename so stuff to make it more readable. Your code could look like this:

FieldInfo field = type.GetField("variableList", 
                             BindingFlags.Instance | 
                             BindingFlags.NonPublic);
List<Variable> variables = (List<Variable>)field.GetValue(instance);

filed is only the FieldInfo , an object that describes the field , it's not the value of the field.

To get the value of the field, use GetValue like this:

var list = (List<Variable>)filed.GetValue(instance);

This returns the value of the field variableList of the instance instance .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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