简体   繁体   English

将FieldInfo转换为C#中的列表

[英]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: 我通过这段代码得到variableList

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: 我尝试将filedvariableList )转换为List<Variable>如下所示:

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 . 您的变量filed装满你的字段元数据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. filed只是FieldInfo ,一个描述该字段的对象,它不是该字段的

To get the value of the field, use GetValue like this: 要获取该字段的值,请使用GetValue如下所示:

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

This returns the value of the field variableList of the instance instance . 这将返回实例instance的字段variableList的值。

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

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