How do I find the actual types of the elements in a list of classes?
Justin Whear via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Aug 13 15:20:35 PDT 2015
On Thu, 13 Aug 2015 21:42:52 +0000, Jack Stouffer wrote:
> 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 :)
Casting actually performs this check for you, returning null if the
object can't be casted, so I'd do this:
foreach (item; parent_list) {
if (auto asA = cast(A)item) {
asA.method();
} else if (auto asB = cast(B)item) {
asB.method2();
}
}
More information about the Digitalmars-d-learn
mailing list