/// <summary> /// Identifies the current platform, and returns a PlatformIdentifier that describes the current platform. /// </summary> /// <returns>A PlatformIdentifier that represents the current platform.</returns> public static PlatformIdentifier GetPlatformIdentifier() { if (_cache != null) { return(_cache); } var ret = new PlatformIdentifier(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { ret.PlatformCodes.Add("linux"); ret.PlatformCodes.Add("unix"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { ret.PlatformCodes.Add("osx"); ret.PlatformCodes.Add("unix"); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ret.PlatformCodes.Add("windows"); } ret.PlatformCodes.Add("generic"); return(_cache = ret); }
/// <summary> /// Constructs an instance of the platform-specific class that implements T interface with the given parameters. /// </summary> /// <typeparam name="T">An interface that has multiple platform-specific implementations.</typeparam> /// <param name="id">The platform identifier to use when looking for the implementation.</param> /// <param name="constructor_params">The set of parameters to be passed to the constructor.</param> /// <returns>A new instance of a class that implements T and matches the provided platform identifier.</returns> public static T GetImplementation <T>(PlatformIdentifier id, params object[] constructor_params) { var T_type = typeof(T); if (!TypesPerInterface.ContainsKey(T_type)) { throw new ArgumentException(); } var types = TypesPerInterface[T_type]; // the platform codes are ordered from most specific to least specific foreach (var platform in id.PlatformCodes) { foreach (var type in types) { if (PlatformsPerType[type].Contains(platform)) { return((T)Activator.CreateInstance(type, constructor_params)); } } } throw new Exception(); }
/// <summary> /// Constructs instances of all the platform-specific classes permitted by the current platform that implement interface T with the given parameters. /// </summary> /// <typeparam name="T">An interface that has multiple platform-specific implementations.</typeparam> /// <param name="constructor_params">The set of parameters to be passed to the constructor.</param> /// <returns>A new instance of a class that implements T and matches the current platform identifier.</returns> public static T GetImplementation <T>(params object[] constructor_params) { return(GetImplementation <T>(PlatformIdentifier.GetPlatformIdentifier(), constructor_params)); }
public static T GetImplementation <T>(PlatformIdentifier id, params object[] constructor_params) => GetImplementations <T>(id, constructor_params).FirstOrDefault();