DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C# (http://www.daniweb.com/forums/forum61.html)
-   -   Reflection (http://www.daniweb.com/forums/thread156942.html)

obscured47 Nov 12th, 2008 6:39 pm
Reflection
 
Hi guys,

I have a type that implements an abstract class that is known at compile time and I want to construct at run time an instance of the type and place the reference in a variable that is of the abstract class's type.

So, to describe it a bit.. Say we have 2 class libraries (called A and B). Library A holds the abstract class and library B holds an implementation of the abstract class. A static variable in the abstract class needs to construct at run time a B object and save it in an A type variable... that is, an A type doesn't know about the existance of B on compile time..

So.. I want to read up on app domains and reflection and all those joys of the .NET but don't have the necessary time right now to do it properly so need you guys to guide me a bit on this. Hope it makes (some) sense.

Cheers!

Rashakil Fol Nov 12th, 2008 9:09 pm
Re: Reflection
 
Pass in to the function in class A a delegate or object that constructs class B.

abstract class A {
  public static void INeedToConstructSomeSubclass(Func<A> subclassDelegate, ...) {
    A blah = subclassDelegate();
    ...
  }
}

Then just call it with
A.INeedToConstructSomeSubclass(() => new B());

You'll need some way of communicating which subclass needs to be constructed -- and it's better and more typesafe to pass in a function than something that uses reflection.

Jugortha Nov 13th, 2008 5:26 am
Re: Reflection
 
Or simply you can use interfaces to play the role of bridge

LizR Nov 13th, 2008 5:44 am
Re: Reflection
 
You can walk through a library looking for classes that descend from something, and then instantiate those.

            CommandTemplate newcmd;
            Console.Write("Loading commands");
            Assembly a = null;
            AssemblyName n = new AssemblyName("mycmds");
            a = Assembly.Load(n);
            foreach (Type t in a.GetTypes())
            {

                if (t.BaseType.Name == "CommandTemplate")
                {
                    newcmd = (CommandTemplate)Activator.CreateInstance(t);

                }
            }
            Console.WriteLine(" Done");

obscured47 Nov 15th, 2008 8:33 am
Re: Reflection
 
Sorry for not replying earlier. What LizR described is what I was pretty much lookingfor. Cheers :)


All times are GMT -4. The time now is 9:06 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC