如何将Reflection中的Field转换为其实际类型?

huangapple go评论71阅读模式
英文:

How can I convert Field from Reflection to its actual type?

问题

这是我的代码:

using System.Reflection;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            var i = this.GetType().GetField("LetterA", BindingFlags.NonPublic | BindingFlags.Instance);
        }

        List<string> LetterA = new List<string>();
        List<string> LetterB = new List<string>();
        List<string> LetterC = new List<string>();
        // 和这样的 List<string> 很多
    }
}

这个类中有很多列表,我想通过反射获取它并向列表中添加值。

正如你所看到的,在我的代码中:

this.GetType().GetField("LetterA", BindingFlags.NonPublic | BindingFlags.Instance)

我可以获取到字段了。但是,当我尝试像这样转换它的实际类型(List<string>)时,会报错:

var i = this.GetType().GetField("LetterA", BindingFlags.NonPublic | BindingFlags.Instance) as List<string>;

如何将其转换为实际类型呢?谢谢。

英文:

Here is my code:

   using System.Reflection;
    
    
    namespace WinFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                var i=this.GetType().GetField(&quot;LetterA&quot;,BindingFlags.NonPublic|BindingFlags.Instance);         
            }
        List&lt;string&gt; LetterA = new List&lt;string&gt;();
        List&lt;string&gt; LetterB = new List&lt;string&gt;();
        List&lt;string&gt; LetterC = new List&lt;string&gt;();
        ///and so on List&lt;string&gt;
    }
}

There are so many lists in the class and I want to get it by Reflection and add value to the list.

As you see, in my code:

this.GetType().GetField(&quot;LetterA&quot;,BindingFlags.NonPublic|BindingFlags.Instance)

I can get the filed now. However, I cannot convert to its actual type(List&lt;string&gt;) for it will reports error when I do it like this:

var i=this.GetType().GetField(&quot;LetterA&quot;,BindingFlags.NonPublic|BindingFlags.Instance) as List&lt;string&gt;;

How can I convert to its actual type? Thank you.

答案1

得分: 2

"现在 i 只表示一个字段,你仍然需要调用 GetValue 来继续。"

"var j = (List<string>)i.GetValue(this);"

英文:

Now that i only represents a field, you still need to call GetValue to proceed.

var j = (List&lt;string&gt;)i.GetValue(this);

huangapple
  • 本文由 发表于 2023年7月18日 11:55:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709434.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定