Skip to content

Instantly share code, notes, and snippets.

@scionwest
Created January 3, 2015 22:36
Show Gist options
  • Save scionwest/174f35945fcb21d8a5cd to your computer and use it in GitHub Desktop.
Save scionwest/174f35945fcb21d8a5cd to your computer and use it in GitHub Desktop.
private static Dictionary<string, Type> cachedStateNames = new Dictionary<string, Type>();
public static TimeOfDayState CreateStateByName(string name, TimeOfDay stateTime)
{
IEnumerable<Type> timeOfDayStateTypes = typeof(TimeOfDayState).GetTypeInfo().Assembly.ExportedTypes
.Where(type => type.GetTypeInfo().BaseType == typeof(TimeOfDayState));
if (cachedStateNames.Count == 0)
{
foreach(Type type in timeOfDayStateTypes)
{
PropertyInfo property = type.GetRuntimeProperty(nameof(Name));
// This is expensive, so we just do it once and cache the results for all states.
cachedStateNames.Add(property.GetValue(Activator.CreateInstance(type)).ToString(), type);
}
}
if (cachedStateNames.ContainsKey(name))
{
return Activator.CreateInstance(cachedStateNames[name]) as TimeOfDayState;
}
else
{
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment