示例#1
0
        /// <summary>
        /// Creates an in memory clone of the specified objectToClone.  The
        /// clone will only have the properties of objectToClone that are
        /// addorned with the specified PropertyAttributeFilter generic type.
        /// </summary>
        /// <typeparam name="PropertyAttributeFilter">The attribute to look for when copying properties</typeparam>
        /// <param name="objectToClone">The object to clone</param>
        /// <param name="concreteAttribute">If true the attributes must be of the specified type and not extenders of the type.</param>
        /// <returns>An in memory type that is not persisted to disk.</returns>
        public static Type CreateDynamicType <PropertyAttributeFilter>(this object objectToClone, out AssemblyBuilder assemblyBuilder, bool concreteAttribute) where PropertyAttributeFilter : Attribute, new()
        {
            Type   objType  = objectToClone.GetType();
            string typeName = objType.Namespace + "." + objType.Name;

            if (DynamicTypeStore.Current.ContainsTypeInfo(typeName) && DynamicTypeStore.Current[typeName].DynamicType != null)
            {
                assemblyBuilder = DynamicTypeStore.Current[typeName].AssemblyBuilder;
                return(DynamicTypeStore.Current[typeName].DynamicType);
            }
            else
            {
                TypeBuilder typeBuilder;
                GetAssemblyAndTypeBuilder(objectToClone, out assemblyBuilder, out typeBuilder);

                foreach (PropertyInfo property in objType.GetProperties())
                {
                    PropertyAttributeFilter attr;
                    if (CustomAttributeExtension.HasCustomAttributeOfType <PropertyAttributeFilter>(property, true, out attr, concreteAttribute))
                    {
                        AddPropertyToDynamicType(typeBuilder, property);
                    }
                }

                Type jsonSafeType = typeBuilder.CreateType();
                Expect.IsNotNull(DynamicTypeStore.Current[typeName], "DynamicTypeInfo was unexpectedly null.");
                DynamicTypeStore.Current[typeName].DynamicType = jsonSafeType;
                return(jsonSafeType);
            }
        }
 protected static bool HasCustomAttributeOfType <T>(MethodInfo method, out T attribute) where T : Attribute, new()
 {
     return(CustomAttributeExtension.HasCustomAttributeOfType <T>(method, out attribute));
 }