A generic way to instantiate QLNet derived classes
In this article we present how you can:
- Make a Calendar QLNet class instantiation based on its name. Ex, i want to instantiate a UnitedStates QLNet Calendar from the string “UnitedStates” (I would obtain such string from an Excel exposed function, for example).
- Retrieve from the QLNet assembly every type derived from the Calendar class ( a use case would be to get this list of calendar names and expose it to a QLNet consumer application).
The sample console project contains a reference to QLNet.dll (you can obtain it from nuget package manager).
QLNet class instantiation
The following code makes it possible to load the QLNet assembly, and create an instance (in the ‘cldr’ variable) of a Calendar derived class identified by its name (“UnitedStates”).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var assemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies(); Calendar cldr = new Canada(); const string calendarname = "UnitedStates"; // Instantiate any Calendar class by its name string foreach (var assemblyname in assemblies) { if (assemblyname.Name == "QLNet") { var qlNetAssembly = Assembly.Load(assemblyname.Name); cldr = (Calendar)qlNetAssembly.CreateInstance("QLNet." + calendarname); } } |
This is quite convenient if you want to avoid a repetition of if/switch, and find a generic way to instantiate those classes from a string.
Get QLNet derived classes names
This second code allows to obtain the full list of calendar names:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Get all calendars derived from Calendar class in the QLNet assembly foreach (var assemblyname in assemblies) { if (assemblyname.Name == "QLNet") { var qlNetAssembly = Assembly.Load(assemblyname.Name); var q = qlNetAssembly.GetTypes().Where(p => p.IsSubclassOf(typeof(Calendar))); foreach (var type in q) { if (!type.ToString().Contains("+")) Console.WriteLine(type.ToString()); } } } Console.Read(); |
Here is the final output (which can then be exposed to users of a QLNet based application for parameters selection):
Leave a Reply