/// <summary> /// Modifies a strongly typed extension contained in the extensible object. Will create the strongly typed extension if it doesn't already exist. /// </summary> /// <typeparam name="T">Type of extensible object</typeparam> /// <typeparam name="TExtension">Type of extension</typeparam> /// <param name="extensibleObject">The CLR extensible object to execute the extension method on.</param> /// <param name="modifyExtensionAction">Modification to perform on the strongly typed extension object.</param> public static void ModifyExtension <T, TExtension>(this IExtensibleObject <T> extensibleObject, Action <TExtension> modifyExtensionAction) where T : IExtensibleObject <T> where TExtension : IExtension <T>, new() { Contract.Requires(extensibleObject != null); Contract.Requires(modifyExtensionAction != null); // Add extension if it does not already exist. TExtension extension; var extensionType = typeof(TExtension); if (extensibleObject.TryGetExtension(extensionType, out var extensionAsInterface)) { extension = (TExtension)extensionAsInterface; } else { extension = new TExtension(); extensibleObject.AddExtension(extension); } // Modify either the existing or new extension object. modifyExtensionAction(extension); }
// PUBLIC METHODS /////////////////////////////////////////////////// #region Extension Methods /// <summary> /// Adds a strongly typed extension by extension CLR type to the extensible object. /// </summary> /// <typeparam name="T">Type of extensible object</typeparam> /// <typeparam name="TExtension">Type of extension</typeparam> /// <param name="extensibleObject">The CLR extensible object to execute the extension method on.</param> /// <param name="extension">The strongly typed extension to add to the extensible object.</param> public static void AddExtension <T, TExtension>(this IExtensibleObject <T> extensibleObject, TExtension extension) where T : IExtensibleObject <T> where TExtension : IExtension <T> { Contract.Requires(extensibleObject != null); extensibleObject.AddExtension(extension); }
/// <summary> /// Creates a strongly typed extension and adds it to the extensible object if it doesn't already exist. Does nothing if it already exists. /// </summary> /// <typeparam name="T">Type of extensible object</typeparam> /// <typeparam name="TExtension">Type of extension</typeparam> /// <param name="extensibleObject">The CLR extensible object to execute the extension method on.</param> public static void CreateExtension <T, TExtension>(this IExtensibleObject <T> extensibleObject) where T : IExtensibleObject <T> where TExtension : IExtension <T>, new() { Contract.Requires(extensibleObject != null); // Install new extension if it does not already exist. var extensionType = typeof(TExtension); if (extensibleObject.TryGetExtension(extensionType, out var extension)) { return; } extension = new TExtension(); extensibleObject.AddExtension(extension); }