use reflection to get back original object from interface

  • Thread starter Thread starter smith
  • Start date Start date
S

smith

How can i convert an interface object back to it's
original object, without knowing original class name....

interface ITest
{
int some_method();
}

public class Test : ITest
{
int some_method()
{
return 0;
}
int some_newMethod()
{
return 1;
}
}

public class Test2 : ITest
{
int some_method()
{
return 0;
}
int some_newMethod()
{
return 1;
}
}

int test()
{
ITest t = new Test2();
return passtest(t);
}

int passtest(ITest ctest)
{
Assembly a = Assembly.GetExecutingAssembly();

// create a 'Test2' class, with out knowing
// original class name...

Object o = a.CreateInstance( ctest.GetType().ToString
(), ...);
return o.some_newMethod();
}


Is this correct... or is there some other more efficient
method or other way to do this?

Thanks
 
smith said:
How can i convert an interface object back to it's
original object, without knowing original class name....

Call the GetType method to determine the original class name. I attached
a simple example for you to look at.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
It's hard to call a method of a specific class without knowing if that
method belongs to that class. Your approach won't work, because o is an
object of type "Object" and will not have the some_NewMethod() exposed.

One way to get around this is using Reflection's GetMethod..

int passtest(ITest ctest)
{
MethodInfo mi = ctest.GetType().GetMethod("some_NewMethod");
return mi.Invoke(ctest, new object[] {});
}

VJ
 
smith said:
How can i convert an interface object back to it's
original object, without knowing original class name....

An object itself never changes type - but your code tries to create a
*new* object of the same type as the original. What are you actually
trying to do? What's the bigger picture here?
 
Back
Top