Created
January 3, 2015 22:36
-
-
Save scionwest/174f35945fcb21d8a5cd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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