How do I find the actual types of the elements in a list of classes?

rumbu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 13 15:27:45 PDT 2015


On Thursday, 13 August 2015 at 21:42:54 UTC, Jack Stouffer wrote:

> 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 :)

It works as long as your module is called "test".

I think this is a better approach:

foreach (item; parent_list) {
         if (auto a = cast(A)item)
             a.method();
         else if (auto b = cast(B)item)
             b.method2();
     }



More information about the Digitalmars-d-learn mailing list