Example #1
0
        /// <summary>
        /// Converts the given object to the type of this converter, using the specified context and culture information.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.</param>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture.</param>
        /// <param name="value">The <see cref="T:System.Object"/> to convert.</param>
        /// <returns>
        /// An <see cref="T:System.Object"/> that represents the converted value.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">
        /// The conversion cannot be performed.
        /// </exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string valueAsString = value as string;

            if (valueAsString != null && valueAsString.StartsWith("(", StringComparison.OrdinalIgnoreCase) && valueAsString.EndsWith(")", StringComparison.OrdinalIgnoreCase))
            {
                if (valueAsString.Equals(_emptyString, StringComparison.OrdinalIgnoreCase))
                {
                    return(TargetType.GetConstructor(Type.EmptyTypes).Invoke(null));
                }
                return(TargetType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).Single().Invoke(new object[] {
                    valueAsString.Substring(1, valueAsString.Length - 2).Split(',').Select(
                        s => TypeConversion.FromString(TargetType.GetGenericArguments()[0], s))
                }));
            }
            return(base.ConvertFrom(context, culture, value));
        }
        /// <summary>
        /// Implements constructors for the proxy class.
        /// </summary>
        /// <param name="typeBuilder">
        /// The <see cref="System.Type"/> builder to use.
        /// </param>
        protected virtual void ImplementConstructors(TypeBuilder typeBuilder)
        {
            ConstructorInfo[] constructors = TargetType.GetConstructors(
                BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (ConstructorInfo constructor in constructors)
            {
                if (constructor.IsPublic || constructor.IsFamily)
                {
                    ConstructorBuilder cb = typeBuilder.DefineConstructor(
                        constructor.Attributes,
                        constructor.CallingConvention,
                        DefineConstructorParameters(constructor));

                    ILGenerator il = cb.GetILGenerator();
                    GenerateConstructor(cb, il, constructor);
                    il.Emit(OpCodes.Ret);
                }
            }
        }