Dynamically creating an object

  • Thread starter Thread starter Doug
  • Start date Start date
D

Doug

I am attempting to create a unit test that can switch between calling
a method from the web service I created or calling the component that
the web service actually calls.

So in my unit test form I have a checkbox that I can use to "turn on
or off" which one I would call and I have code something like this:

if (chkUseWs.Checked == true)
{
WebReference.WebClass o = new WebReference.WebClass();
o.Method;
}
else
{
ComponentReference y = new ComponentReference();
y.Method();
}

--WebReference, WebClass and ComponentReference are all made up
names... :)

Anyhow, I'd like to instead just create one variable and assign it to
either the web reference or the component reference based on whether
the checkbox is checked.

I've tried creating an object variable like this:

object o = new WebReference.WebClass();
or
object o = new ComponentReference();

but that failed.

This also failed:

if (chkUseWS.Checked == true)
{
WebReference.WebClass o = new WebReference.WebClass();
}
else
{
ComponentReference o = new ComponentReference();
}

o.Method();

Is there a way to do what I'm trying to do?
 
Here's some code that lets you call a method with the same signature on two
unrelated classes. ClassA and ClassB are random, but they could apply to
your business object and the Web service proxy object generated in the
project. If you're loading object types from other assemblies, you'll have
to do something like 'type =
Assembly.LoadFile("assemblyPath").GetType("className");' There are
optimizations you can do around this, but this code should help you get
started.

using System;

using System.Reflection;

namespace ConsoleApplication1

{

class ClassA

{

public ClassA() {}

public string GetString()

{

return "ClassA";

}

}

class ClassB

{

public ClassB() {}

public string GetString()

{

return "ClassB";

}

}



/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main(string[] args)

{

bool useClassA = true;

Type type;

object obj;

if (useClassA)

{

type = Type.GetType("ConsoleApplication1.ClassA");

obj = new ClassA();

}

else

{

type = Type.GetType("ConsoleApplication1.ClassB");

obj = new ClassB();

}

// More info on InvokeMember at

//
http://msdn.microsoft.com/library/d...tml/frlrfsystemtypeclassinvokemembertopic.asp

string result = (string) type.InvokeMember("GetString", BindingFlags.Default
| BindingFlags.InvokeMethod, null, obj, null);


Console.WriteLine(result);

}

}

}
 
Back
Top