1
100
1. This program shouldn't work at all.
*Main* is static method and there is no *this*.
2.Beside my first remark if we look at the reflection usage:
System.Reflection.FieldInfo fi =
Type.GetType("ConsoleApplication4.reflection") .GetField("mstr");
string temp = (string)fi.GetValue(null);
MessageBox.Show("get string {0}", temp);
This is ok
/////////// THIS IS NOT WORKING \\\\\\\\\\\
Type.GetType("ConsoleApplication4.reflection") .GetField("textbox1");
You have forgotten *fi = ....*. You are using FieldInfo for the *mstr* field.
BTW this should return *null* since IFAIK the default binding is case sensitive. You shoud use "textBox1";
string temp = (string)fi.GetValue("Text");
You are trying ot get a value for *mstr* field of object of type String. String doesn't have this field. GetValue exepects object which field value will be returned. The type of this object has to be type that declares or inhertis the field. String doesn't declares the field nor inherits from reflection class. This is the exception that you've got.
The correct code should look something like the following:
reflection r = new reflection();
FiledInfo fi = Type.GetType("ConsoleApplication4.reflection") ..GetField("textBox1");
//Alternatives for obtaining type object :
//typeof(ConsoleApplication4.reflection)
//r.GetType();
TextBox tb = (TextBox))fi.GetValue(r);
MessageBox.Show("get string {0}", tb.Text);
HTH
B\rgds
100
*Main* is static method and there is no *this*.
2.Beside my first remark if we look at the reflection usage:
System.Reflection.FieldInfo fi =
Type.GetType("ConsoleApplication4.reflection") .GetField("mstr");
string temp = (string)fi.GetValue(null);
MessageBox.Show("get string {0}", temp);
This is ok
/////////// THIS IS NOT WORKING \\\\\\\\\\\
Type.GetType("ConsoleApplication4.reflection") .GetField("textbox1");
You have forgotten *fi = ....*. You are using FieldInfo for the *mstr* field.
BTW this should return *null* since IFAIK the default binding is case sensitive. You shoud use "textBox1";
string temp = (string)fi.GetValue("Text");
You are trying ot get a value for *mstr* field of object of type String. String doesn't have this field. GetValue exepects object which field value will be returned. The type of this object has to be type that declares or inhertis the field. String doesn't declares the field nor inherits from reflection class. This is the exception that you've got.
The correct code should look something like the following:
reflection r = new reflection();
FiledInfo fi = Type.GetType("ConsoleApplication4.reflection") ..GetField("textBox1");
//Alternatives for obtaining type object :
//typeof(ConsoleApplication4.reflection)
//r.GetType();
TextBox tb = (TextBox))fi.GetValue(r);
MessageBox.Show("get string {0}", tb.Text);
HTH
B\rgds
100