D
Dan Dorey
My goal is to pass in an assembly and have the method return an
instance of any classes that inherit from the generic type T.
My problem is that I'm unable to cast from the result of
Activator.CreateInstance(curType) to T even though curType is a
concrete class of T (T is abstract in this case). I'm unsure why I
can't make this cast. In another method where I don't have the
restriction of T being a class, this approch works fine when T is an
interface.
I kind of feel like I'm going about this the wrong way, so if anyone
has suggestions on a better approach, please let me know
Thanks,
Dan
public static List<T> GetClassesByClassName<T>(Assembly assembly,
object[] classParams) where T : class
{
List<T> ret = new List<T>();
foreach (Type curType in assembly.GetTypes())
{
if (InheritsFrom(curType, typeof(T)) &&
curType.IsAbstract == false)
{
if (classParams == null)
{
ret.Add((T)Activator.CreateInstance(curType));
}
else
{
ret.Add((T)Activator.CreateInstance(curType, classParams));
}
}
}
return ret;
}
private static bool InheritsFrom(Type curType, Type targetType)
{
bool ret = false;
while (curType.FullName != "System.Object")
{
if (curType.FullName == targetType.FullName)
{
ret = true;
break;
}
else
{
curType = curType.BaseType;
}
}
return ret;
}
instance of any classes that inherit from the generic type T.
My problem is that I'm unable to cast from the result of
Activator.CreateInstance(curType) to T even though curType is a
concrete class of T (T is abstract in this case). I'm unsure why I
can't make this cast. In another method where I don't have the
restriction of T being a class, this approch works fine when T is an
interface.
I kind of feel like I'm going about this the wrong way, so if anyone
has suggestions on a better approach, please let me know
Thanks,
Dan
public static List<T> GetClassesByClassName<T>(Assembly assembly,
object[] classParams) where T : class
{
List<T> ret = new List<T>();
foreach (Type curType in assembly.GetTypes())
{
if (InheritsFrom(curType, typeof(T)) &&
curType.IsAbstract == false)
{
if (classParams == null)
{
ret.Add((T)Activator.CreateInstance(curType));
}
else
{
ret.Add((T)Activator.CreateInstance(curType, classParams));
}
}
}
return ret;
}
private static bool InheritsFrom(Type curType, Type targetType)
{
bool ret = false;
while (curType.FullName != "System.Object")
{
if (curType.FullName == targetType.FullName)
{
ret = true;
break;
}
else
{
curType = curType.BaseType;
}
}
return ret;
}