Maybe my brain is not working properly and i cant see the forest because of the trees ...
Currently I have a class called CheckManager
which searches the current assembly for a certain type called UserControlBaseCheck
which is declared in a separate library. (this works fine)
I do have a variable AllChecks of type SortedDictionary<IBaseCheck, UserControlBaseCheck>
(and a custom IComparer
class which know's how to sort IBaseCheck
).
This variable AllChecks is used to populate a Stack
. The stack is then worked through by a User, once it is depleted, it get's filled again with new instances of all classes inside the AllChecks
variable. And the whole game starts again.
Currently i solved it this way:
//declaration of my container with all checks
private static SortedDictionary<IBaseCheck, UserControlBaseCheck> AllChecks =
new SortedDictionary<IBaseCheck, UserControlBaseCheck>(new Comparer());
// this is how i call the method to find all classes which inherit from the type
FindDerivedTypes(Assembly.GetExecutingAssembly(), typeof(UserControlBaseCheck));
//this is the definition... it seems to me bit odd that I have to use the Activator
//and create an instance and cast it to the interface just to do
//what i want to do...
//is there any other / easier / better way of doing so?
public static IList<IBaseCheck> FindDerivedTypes(Assembly assembly,Type baseType)
{
//FYI: until the '.Select' I get a list of type List<System.Type>
List<IBaseCheck> o = assembly.GetTypes()
.Where(t => t != baseType && baseType.IsAssignableFrom(t))
.Select(type => Activator.CreateInstance(type) as IBaseCheck)
.ToList();
return o;
}
i find it odd that I have to create first an instance of the type just to use/convert it to an interface. Why can't i just do: .Select(x=> x as IBaseCheck)
I mean i have already a list with object of type List<System.Type>
and it seems to me bit overkill what i am doing just to get my list of type IBaseCheck
(List<IBaseCheck>
)
Aucun commentaire:
Enregistrer un commentaire