using System; using System.Reflection; namespace ShwasherSys.ReflectionMagic { public static class UsingDynamicExtensions { /// /// Wraps the specified object in a dynamic object that allows access to private members. /// /// The object to wrap /// The wrapped object. /// /// Does not wrap null, , primitive types, and already wrapped objects. /// /// public static dynamic AsDynamic(this object o) { // Don't wrap primitive types, which don't have many interesting internal APIs if (o == null || o.GetType().GetTypeInfo().IsPrimitive || o is string || o is DynamicObjectBase) return o; return new DynamicObjectInstance(o); } /// /// Wraps the specified type in a dynamic object which allows easy instantion through the method. /// /// The type to wrap. /// The wrapped type. /// public static dynamic AsDynamicType(this Type type) { return new DynamicObjectStatic(type); } /// /// Gets the type with the specified name from the specified assembly instance, and returns it as a dynamic object. See also . /// /// The assembly instance to search for the type. /// The type name. /// The wrapped type. /// public static dynamic GetDynamicType(this Assembly assembly, string typeName) { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); return assembly.GetType(typeName).AsDynamicType(); } /// /// Tries to instantiate the type with the specified type name from the specified assembly instance using the specified constructor arguments. /// /// The assembly instance to search. /// The full type name. /// The arguments to pass to the constructor. /// /// Thrown when no suitable constructor can be found. public static dynamic CreateDynamicInstance(this Assembly assembly, string typeName, params object[] args) { if (args == null) throw new ArgumentNullException(nameof(args)); return assembly.GetDynamicType(typeName).New(args); } } }