Hi,
Reflection has the ability for a program to dynamically inspect itself, is possibly one of the most powerful features of modern programming languages like C# and Java. The following is a simple example of how to interrogate the current C# assembly, locate all the classes that are derived from a base class, and then dynamically created and executed an instance of the class.
But I need to create an Instance using a variable by passing a parameter class name as string. See the following code:
you can call this by GetObject("Company","");// company is a class inherited from BaseOB
public static object GetObject(string nameClass, string request){
Assembly asm = Assembly.GetExecutingAssembly(); // take the current assembly foreach (Type type in asm.GetTypes()) // for each type Class, Form { if (type.IsClass && type.Name == nomeClasse ) //find all the Types that are “Classes” { PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo prop in properties) { string s = prop.Name; //will return the name of each properties } ConstructorInfo ci = type.GetConstructor(new Type[] { }); Company tmp = (Company)ci.Invoke(new Object[] { }) ; //BaseOB objBase = (Company)ci.Invoke(new Object[] { }) ; tmp.CompanyName = "OT"; tmp.run(); //objBase.run(); } }
return new object(); }
This type of Conversion works but if i do something like this in my code then doesn work. it shows runtime exception that is not possible to convert in BaseOB type from basic object t ype. Somthing like this.
string sType = "System.Int32"; object o1 = "123"; object o2 = Convert.ChangeType(o1, Type.GetType(sType)); Type t = o2.GetType(); // this returns Int32 Type
Let me know if you solved this kind of problem. Thanks a lot
MJ FerdousProject Manager, Congral LLCTechnical Author, DevMedia, Brazil
I got an article link from my colleague to solve my problem. To resolve this problem just use the Generics (obviously for versions of the framework from 2.0 onwards). Since i am using 1.1 i can't use generics.
I used the following code to set values in the properties without converting
Object o = Activator.CreateInstance( type ); System.Reflection.PropertyInfo p_i; string CompanyCodedd = "CompanyCode"; p_i = type.GetProperty("CompanyName"); p_i.SetValue(o,"OT",null);
nice to hear that you get the solution .......but some times reflection is lil more coslty. If you wanna to convert a type to where you r going to mapped the property then I will suggest dont go for the costly operations.You can use expression tree in place of reflection .You can take a look on this blog-
http://morshedanwar.wordpress.com/2009/03/24/type-convertion-using-expression-in-place-of-reflection-cnet/
binito .... Morshed Anwar (http://morshedanwar.wordpress.com/)