Hello,
The short answer is: You can't. Since the text name of the class is
only known at runtime and you determine the casting operators at
compile-time there is no way the compiler can know in advance to what
type you object should be cast.
If you *do* know the type at compile time, the code would be as
follows:
Type[] parms = { typeof(System.Data.OleDb.OleDbDataReader) };
Type theTblType = typeof(MyClassName);
ConstructorInfo methodCreate = theTblType.GetConstructor(parms);
object[] argumentItems = { dr };
object rec = methodCreate.Invoke(theTblType, argumentItems);
MyClassName cast = (MyClassName)rec;
However, it looks like you are trying to accomplish a plugin type of
thing and fortunately there is a way to accomplish that. Let's say you
have a number of plugins that can generate a welcome string using the
datareader (yeah, it's lame but it works). The code should look as
follows:
public abstract class BasePlugin {
public BasePlugin(IDataReader reader) { // Why tie yourself to
OleDB?
// (..)
}
public abstract string GenerateWelcome();
}
public abstract class Plugin1 : Plugin {
public override string GenerateWelcome() {
return "Welcome world"; // You could also use the data reader but
this is shorter
}
}
public abstract class Plugin2 : Plugin {
// (code omitted)
}
Now you have several plugins, which could even reside in several
different assemblies. The code actually using the plugin would look
like this:
Type[] parms = { typeof(System.Data.OleDb.OleDbDataReader) };
Type theTblType = Type.GetType("Plugin1");
ConstructorInfo methodCreate = theTblType.GetConstructor(parms);
object[] argumentItems = { dr };
object rec = methodCreate.Invoke(theTblType, argumentItems);
Plugin plugin = (Plugin)rec;
Console.WriteLine(plugin.GenerateWelcome());
Note there is no compile-time checking of the type you supply to the
type.gettype() method. Instead of "Plugin1", you could also pass the
name of a type which is not a subclass of Plugin. This would generate
an exception when trying to instantiate the type (or when trying to
cast to plugin, if the type happens to have a constructor taking an
IDataReader).
Regards,
Bram
When creating a class using the Invoke method of the ConstructorInfo, this
returns and object. I am wondering how I can reclass this object type into
the specific class type. Since I only have the "text" name of the class to
begin with, how can I make an object reclassed into an object of the class
which is of the text name that I have.
Type[] parms = { typeof(System.Data.OleDb.OleDbDataReader) };
Type theTblType = Type.GetType("MyClassName");
ConstructorInfo methodCreate = theTblType.GetConstructor(parms);
object[] argumentItems = { dr };
object rec = methodCreate.Invoke(theTblType, argumentItems);
How do I reclass "rec" into a type of "MyClassName" with only the text
name of
the class?
Thanks in advance for your assistance!!!