Get all Comps within a ThingWithComps that derive from a given class/interface

Started by justarandomgeek, April 04, 2015, 01:50:00 AM

Previous topic - Next topic

justarandomgeek

I'm pretty sure this is currently impossible, after looking around for it for a while, but I'd like to be able to get a List<ThingComp> of all the comps on a given ThingWithComps that derive from one of my base classes/interfaces. Specifically, I want to get List<CompSignal> or List<ICompSignal>and have it contain all the direction-specific subclasses too. My goal is to make it so that CompSignal connects on any sides that aren't already connected by direction-specific subclasses, without having to actually specifically check every possible variation in the code (That's 7 so far, N/S/E/W, NS, EW, and N+Source, but I expect that list to grow over time).

Is there a way to get all Comps of a given supertype (or just all, I'll filter it myself...) from a ThingWithComps?

justarandomgeek

For anyone else who finds this useful, I found that I was able to add an extension method to ThingWithComponents that uses reflection to get at the private field comps to achieve this:


public static List<T> GetAllComps<T>(this ThingWithComponents t) where T:class
{
var field = typeof(ThingWithComponents).GetField("comps", BindingFlags.NonPublic|BindingFlags.Instance);
var comps = (List<ThingComp>)field.GetValue(t);
return comps.ConvertAll(c=>c as T).FindAll(c=>c!=null);
}


This is all kinds of evil, and we really shouldn't do it, but it does work! You could also set the constraint to be T:ThingComp, but this prevents using an interface to select your Comps. If you don't use interfaces on Comps, you should probably use T:ThingComp.