英文:
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("LetterA",BindingFlags.NonPublic|BindingFlags.Instance);
}
List<string> LetterA = new List<string>();
List<string> LetterB = new List<string>();
List<string> LetterC = new List<string>();
///and so on List<string>
}
}
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("LetterA",BindingFlags.NonPublic|BindingFlags.Instance)
I can get the filed now. However, I cannot convert to its actual type(List<string>
) for it will reports error when I do it like this:
var i=this.GetType().GetField("LetterA",BindingFlags.NonPublic|BindingFlags.Instance) as List<string>;
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<string>)i.GetValue(this);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论