//you can use the Activator.Create instance to do so.
using System;
using System.Collections.Generic;
using System.Text;
namespace Labs1
{
class Program
{
static void Main(string[] args)
{
string TypeName = "DerivedTest";
string NmSpace = "Labs2";
//gets the System.Type of the control name (must be fully qualified)
Type t = Type.GetType(NmSpace + "." + TypeName);
//Uses the 'Activator' to create a new instance of the specified type
Labs2.Test obj1 = (Labs2.Test)Activator.CreateInstance(t);
//Now, "DerivedTest" is an instance of that type
obj1.Method();
NmSpace = "Labs3";
t = Type.GetType(NmSpace + "." + TypeName);
Labs3.ITest obj2 = (Labs3.ITest) Activator.CreateInstance(t);
obj2.Method();
Console.ReadLine();
}
}
}
namespace Labs2
{
public abstract class Test
{
public virtual void Method()
{
Console.WriteLine("BasedTest2");
}
}
public class DerivedTest : Test
{
public override void Method()
{
Console.WriteLine("DerivedTest2");
}
}
}
namespace Labs3
{
interface ITest
{
void Method();
}
public class Test : ITest
{
public virtual void Method()
{
Console.WriteLine("BasedTest3");
}
}
public class DerivedTest : Test
{
public override void Method()
{
Console.WriteLine("DerivedTest3");
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Labs1
{
class Program
{
static void Main(string[] args)
{
string TypeName = "DerivedTest";
string NmSpace = "Labs2";
//gets the System.Type of the control name (must be fully qualified)
Type t = Type.GetType(NmSpace + "." + TypeName);
//Uses the 'Activator' to create a new instance of the specified type
Labs2.Test obj1 = (Labs2.Test)Activator.CreateInstance(t);
//Now, "DerivedTest" is an instance of that type
obj1.Method();
NmSpace = "Labs3";
t = Type.GetType(NmSpace + "." + TypeName);
Labs3.ITest obj2 = (Labs3.ITest) Activator.CreateInstance(t);
obj2.Method();
Console.ReadLine();
}
}
}
namespace Labs2
{
public abstract class Test
{
public virtual void Method()
{
Console.WriteLine("BasedTest2");
}
}
public class DerivedTest : Test
{
public override void Method()
{
Console.WriteLine("DerivedTest2");
}
}
}
namespace Labs3
{
interface ITest
{
void Method();
}
public class Test : ITest
{
public virtual void Method()
{
Console.WriteLine("BasedTest3");
}
}
public class DerivedTest : Test
{
public override void Method()
{
Console.WriteLine("DerivedTest3");
}
}
}
No comments:
Post a Comment