Friend encountered a problem:
Read from the character string in the text ( "San", "20" ...), a string of known type ( "string", "int" ....)
Converted into the desired class object.
The data is large, frequent use may affect the efficiency of reflection, so a small demo written as follows:
Person class:
. 1 class the Person 2 { . 3 public String XM { GET ; SET ;} . 4 public int NL { GET ; SET ;} . 5 public void ShowMe () . 6 { . 7 Console.WriteLine ( " I " + XM + " , I am ." + NL + " years old. " ); 8 } 9 }
Conversion helper class:
class Convert_Helper { static PropertyInfo [] PS; // fed type, all public properties of the reflective back public static void get_Props <T> (T TT) { PS = tt.GetType () GetProperties ();. } // into character string and type, type of return value of the specified public static Dynamic change_Type ( String X, String x_type) { IF (x_type == " int " ) { return int .Parse (X); } returnX; } // into objects, and type of the assigned object. public static void get_object ( Dynamic obj, String [] MyValues, String [] ValueType) { for ( int I = 0 ; I <myvalues.Length; I ++ ) { PS [I] .setValue (obj, change_Type (MyValues [I] , ValueType [I]), null ); } } }
The main program:
1 static void Main(string[] args) 2 { 3 string[] v1,t1; 4 List<Person> mylist=new List<Person>(); 5 Person t; 6 Convert_Helper.get_Props(new Person()); 7 8 t = new Person(); 9 v1=new string[2]{"张三","20"}; 10 t1 = new string[2] { "string", "int" }; 11 Convert_Helper.get_Object(t,v1,t1); 12 mylist.Add(t); 13 14 t = new Person(); 15 v1 = new string[2] { "李四", "18" }; 16 t1 = new string[2] { "string", "int" }; 17 Convert_Helper.get_Object(t, v1, t1); 18 mylist.Add(t); 19 20 foreach (var item in mylist) 21 { 22 item.showme(); 23 } 24 Console.ReadKey(); 25 }
This, even if the text is a two-dimensional array or other bulk form, slightly modified main routine; if the attribute does not correspond to get_Props method slightly modified.
Readers should not be difficult yourself.