Reflection

  • Thread starter Thread starter OldButStillLearning
  • Start date Start date
O

OldButStillLearning

I am trying to use reflection to create an instance of a class which I have a
"text" name to work with to create the object.

The Class that I want to create and instance of has a constructor which
takes a "DataRow" as input.

So as I understand it, one of the things I have to do is create an object
array contains all of the "Types" that are used in the constructor. I have
tried to create an instance of the Type by using the following command:
Type.GetType("System.Data.DataRow", true, true)

This apparently defaults information which was not supplied and I apparently
have to supply more information as part of the 1st parm of the GetType to
properly identify where the information is which will allow the "Type" to be
created.

I have located the System.Data.dll and selected properties on this in
windows explorer. I believe that I must provide Version, but there are a few
specified in the properties, which do I select? I believe I have to supply
Culture and PublicKeyToken, not sure what to provided - maybe not all of
these are required for it to be successful, not sure.

Secondly - Can I programatically retrieve this information so that if this
changes with new releases of the Framework I will not have to change my
program and recompile?

Thanks in advance for your assistance!!!!
 
Hi,

Why do you not use VB6 that does all what you are doing automaticly.

It is not from this time, however as you want to use reflection, it is
almost the same as VB for Net with Option Strict off.

Both not recomended by the way.

Cor
 
Hi,

I hope i understood Your question well. So as i think You have a class like
this :
class SomeClass
{
public SomeClass(DataRow dr)
{ ... }
}

To create an instance of this class by reflection do the following :
1., get the Type representing Your class
2., get the constructor for Your type
3., invoke it

This can be achieved like this :
string typeName = //full name of the class You wish to create an
instance of
Type t = Type.GetType(typeName); // get the Type representing
Your type
// get the constructor of the type, which takes 1 DataRow as
parameter
// here You can use the typeof operator to get the Type
representing DataRow
// (assuming You referenced its assembly in Your project)
ConstructorInfo ci = t.GetConstructor(new Type[] {
typeof(DataRow) });
DataRow dr = // this will be the parameters value
// create new instance
SomeClass sc = ci.Invoke(new object[] { dr }) as SomeClass;

This is an example only. You might also want to look at other overloads of
GetConstructor.

Hope You find this useful.
-Zsolt
 
Back
Top