Exemple #1
0
        /// <summary>
        ///     This extension uses the DuckTyper to transform an object into a given interface or type.
        /// </summary>
        /// <typeparam name="TInterface"></typeparam>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static TInterface As <TInterface>(this object instance)
        {
            if (typeof(TInterface).IsDelegate())
            {
                // find a function in this object that matches the delegate that we are given
                // and return that instead.
                if (instance.GetType().IsDelegate())
                {
                    if (typeof(TInterface).IsDelegateAssignableFromDelegate(instance.GetType()))
                    {
                        return(((Delegate)instance).CreateProxiedDelegate <TInterface>());
                    }
                    throw new Exception("Delegate '{0}' can not be created from Delegate '{1}'.".format(typeof(TInterface).NiceName(), instance.GetType().NiceName()));
                }

                var instanceSupportsMethod = GenerateInstanceSupportsMethod(instance);
                var instanceType           = instance.GetType();

                var instanceMethods    = instanceType.GetPublicMethods();
                var instanceFields     = instanceType.GetPublicDelegateFields();
                var instanceProperties = instanceType.GetPublicDelegateProperties();

                if (!instanceSupportsMethod(typeof(TInterface).Name))
                {
                    throw new Exception("Generation of Delegate '{0}' not supported from object.".format(typeof(TInterface).NiceName()));
                }

                var method = instanceMethods.FindMethod(typeof(TInterface));
                if (method != null)
                {
                    return(instance.CreateProxiedDelegate <TInterface>(method));
                }
                var instanceDelegate = instanceFields.FindDelegate(instance, typeof(TInterface)) ?? instanceProperties.FindDelegate(instance, typeof(TInterface));
                if (instanceDelegate != null)
                {
                    if (instanceDelegate is TInterface)
                    {
                        return((TInterface)(object)instanceDelegate);
                    }
                    return(instanceDelegate.CreateProxiedDelegate <TInterface>());
                }
                return((TInterface)(object)typeof(TInterface).CreateEmptyDelegate());
                // throw new Exception("Delegate '{0}' not matched in object.".format(typeof (TInterface).NiceName()));
            }
            return(DynamicInterface.DynamicCast <TInterface>(instance));
        }
Exemple #2
0
 public static TInterface Extend <TInterface>(this object obj, params object[] objects)
 {
     return(DynamicInterface.DynamicCast <TInterface>(objects, obj));
 }