Say I have a class CoolStorageClass
, which inherits from StorageClassBase
:
public abstract class StorageClassBase
{
//does something
}
public class CoolStorageClass : StorageClassBase
{
}
Then I have a generic abstract BaseClass<T>
(which implements interface IBase<T>
, which is probably not important for the question). It is important, that T
can only be of type StorageClassBase
.
public abstract class BaseClass<T> : IBase<T> where T : StorageClassBase
{
}
Then I have the implementation of the BaseClass
with T
as CoolStorageClass
in the form of CoolClass
:
public class CoolClass : BaseClass<CoolStorageClass>
{
}
I want to select all of my object, which are implementing the BaseClass<StorageClassBase>
abstract class.
-
does it make sense to check the generic of
BaseClass
? I mean, I could have classes, which inherit fromBaseClass<DifferentStorageClassBase>
... -
how do I check if a
Type
implementsBaseClass<StorageClassBase>
? I have found following [answer][1], but it does not check the type of the generic parameter. So I modified it into this:public static class TypeExtensions { //https://stackoverflow.com/a/457708 public static bool HasBaseClassOf(this Type t, Type toCheck, Type genericParameter) { while ((t != null) && (t != typeof(object))) { var cur = t.IsGenericType ? t.GetGenericTypeDefinition() : t; if (toCheck == cur) { //also check whether the generic types match if (t.GenericTypeArguments[0].IsSubclassOf(genericParameter)) { return true; } } t = t.BaseType; } return false; } }
But this only checks for one generic type, and I don't understand why I have to check t.GenericTypeArguments
instead of cur.GenericTypeArguments
.
-
What is the correct way to check for all the generic type arguments and the
BaseClass
? -
Currently I have to call the function like this:
o.GetType().HasBaseClassOf(typeof(ProxyBase<>), typeof(ProxyDataPointBase))
. How should I modify the function to be able to call it like this:o.GetType().HasBaseClassOf(typeof(ProxyBase<ProxyDataPointBase>))
? [1]: https://stackoverflow.com/a/457708
Aucun commentaire:
Enregistrer un commentaire