Hello,
I'm new to C# and have a question regarding factoring through
reflection.
I have a database filled with data represented by name and value pairs.
Each name has a identically named class in my program. Each of these
classes is a descendant of a 'DataType' class. After reading about
reflection, I though I could use this naming in my advantage:
namespace Something
{
// base class of all types for the factory
public abstract class DataType
{
public abstract string Value { get; set; }
public abstract bool TryParse(string a);
};
public static class TypeFactory
{
static TypeFactory()
{
// Create a list of creatable types.
foreach (Module m in
Assembly.GetExecutingAssembly().GetModules())
foreach (Type t in m.GetTypes())
if ( (!t.IsAbstract) &&
(t.IsSubclassOf(typeof(DataType))))
TypeList.Add(t.Name.ToUpper(), t);
}
// Create the DataType by name
public static DataType CreateByName(string aName)
{
Type d = TypeList[aName.ToUpper()];
return (d==null)? null : (DataType)d.GetConstructor(
System.Type.EmptyTypes).Invoke(null);
}
public static SortedList<string, Type> TypeList =
new SortedList<string,Type>();
}
}
This works fine, but the static constructor must iterate through all
types in the assembly, of which most are not DataType descendants. This
problem will grow as the program grows.
I know reflection is not the fastest way, but most alternatives I tried
resulted in a lot of repetetive programming, since the number of
DataType classes is large.
Does anybody know a more efficient way to extract the DataType
descendents from the assembly?
Rob