On Thursday, 13 August 2015 at 20:28:33 UTC, Adam D. Ruppe wrote:
On Thursday, 13 August 2015 at 20:23:56 UTC, Jack Stouffer
wrote:
As far as I can tell, there is no way to know the actual type
of each of the objects in the list to be able to print:
Cast it to Object first, then do the typeid and it will get the
dynamic class type. Since Parent is an interface, typeid works
differently.
I wrote about this in more detail recently here:
http://stackoverflow.com/questions/31563999/how-to-get-classinfo-of-object-declared-as-an-interface-type/31564253#31564253
Thanks, that worked, and based on your answer, I was able to fix
my real problem: dynamically calling different methods on each
object in the list based on its type. So, using the above code as
an example, I am able to call method if the object is of type A
and method2 if the object is of type B:
interface Parent {
void method();
}
class A : Parent {
void method() {}
this() {}
}
class B : Parent {
void method() {}
void method2() {}
this() {}
}
void main() {
import std.stdio;
import std.string;
Parent[] parent_list = [];
parent_list ~= new A();
parent_list ~= new B();
foreach (item; parent_list) {
string class_name = (cast(Object)
item).classinfo.name;
if (class_name == "test.A") {
(cast(A) item).method();
} else if (class_name == "test.B") {
(cast(B) item).method2();
}
}
}
This is a dirty hack, but I don't care, it works :)