使用“反射”从另一个类获取 int 不起作用

本文关键字:获取 int 不起作用 另一个 反射 使用 | 更新日期: 2023-09-27 18:28:34

编辑:我找到了错误的源头。我用type字符串指向字符串而不是整数调用classTwo()

所以我正在尝试使用反射从另一个类中获取一个 int。

当我从另一个类获取字符串时,它有效,但当我尝试获取 int 时则不行。

这是我的代码:

class classOne //In its own file (classOne.cs)
{
    public int myInt = 5;
    public string myString = "Hello World";
    new classTwo(this, "myInt").show(); //classTwo is actually a form.
}
class classTwo //In its own file (classTwo.cs)
{
    classOne frm;
    int kind1;
    string kind2;
    string type;
    public classTwo(classOne frm, string type)
    {
        this.frm = frm;
        this.type = type;
    }
    //Doesn't work:
    this.kind1 = Convert.ToInt32(this.frm.GetType().GetField(this.type).GetValue(this.frm));
    //Works:
    this.kind2 = Convert.ToString(this.frm.GetType().GetField("myString").GetValue(this.frm));
}

这行不通。当我使用 Convert.ToString 时它可以工作,但是当我使用它时,当我运行它时它会抛出错误:


格式异常未处理

输入字符串的格式不正确。


有人可以向我解释我做错了什么,并给出解释性的解决方法(如果可能的话(吗?

使用“反射”从另一个类获取 int 不起作用

完美运行

class classOne //In its own file (classOne.cs)
{
    public int myInt = 5;
    public string myString = "Hello World";
    public void test()
    {
        var obj = new classTwo(this, "myInt");
        obj.test();
    }
}
class classTwo //In its own file (classTwo.cs)
{
    classOne frm;
    int kind1;
    string kind2;
    string type;
    public classTwo(classOne frm, string type)
    {
        this.frm = frm;
        this.type = type;
    }
    //Doesn't work:
    public void test()
    {
        //Doesn't work:
        this.kind1 = Convert.ToInt32(this.frm.GetType().GetField(this.type).GetValue(this.frm));

        this.kind2 = Convert.ToString(this.frm.GetType().GetField("myString").GetValue(this.frm));
    }
}