Tuesday, 20 August 2013

Using "Reflection" to get int from another class isn't working

Using "Reflection" to get int from another class isn't working

EDIT: I found the source of the error. I called classTwo() with type
string pointing to a string, not an integer.
So I'm trying to get an int from another class using Reflection.
It works when I get a string from another class, but not when I try to get
an int.
Here is my code:
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));
}
This doesn't work. It works when I use Convert.ToString, but when I use
this, it throws an error when I run it:



FormatException was Unhandled
Input string was not in a correct format.



Can someone please explain to me what I'm doing wrong, and give an
explained fix (if possible)?

No comments:

Post a Comment