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

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

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

问题

这是我的代码:

  1. using System.Reflection;
  2. namespace WinFormsApp1
  3. {
  4. public partial class Form1 : Form
  5. {
  6. public Form1()
  7. {
  8. InitializeComponent();
  9. }
  10. private void Form1_Load(object sender, EventArgs e)
  11. {
  12. var i = this.GetType().GetField("LetterA", BindingFlags.NonPublic | BindingFlags.Instance);
  13. }
  14. List<string> LetterA = new List<string>();
  15. List<string> LetterB = new List<string>();
  16. List<string> LetterC = new List<string>();
  17. // 和这样的 List<string> 很多
  18. }
  19. }

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

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

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

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

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

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

英文:

Here is my code:

  1. using System.Reflection;
  2. namespace WinFormsApp1
  3. {
  4. public partial class Form1 : Form
  5. {
  6. public Form1()
  7. {
  8. InitializeComponent();
  9. }
  10. private void Form1_Load(object sender, EventArgs e)
  11. {
  12. var i=this.GetType().GetField(&quot;LetterA&quot;,BindingFlags.NonPublic|BindingFlags.Instance);
  13. }
  14. List&lt;string&gt; LetterA = new List&lt;string&gt;();
  15. List&lt;string&gt; LetterB = new List&lt;string&gt;();
  16. List&lt;string&gt; LetterC = new List&lt;string&gt;();
  17. ///and so on List&lt;string&gt;
  18. }
  19. }

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:

  1. 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:

  1. 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.

  1. 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:

确定