public void ConvertTo() { MarginsConverter mc = new MarginsConverter(); Guid guid = Guid.NewGuid(); CultureInfo culture = CultureInfo.InvariantCulture; Margins margins = new Margins() { Left = 1, Right = 2, Top = 3, Bottom = 4 }; // try once with then once without context for (var context = new MyTypeDescriptorContext(); context != null; context = null) { Assert.Equal("1;2;3;4", mc.ConvertTo(context, culture, "1;2;3;4", typeof(string))); object converted = mc.ConvertTo(context, culture, margins, typeof(string)); Assert.IsType <string>(converted); Assert.Equal(',', culture.TextInfo.ListSeparator[0]); Assert.Equal("1, 2, 3, 4", converted); converted = mc.ConvertTo(context, culture, margins, typeof(InstanceDescriptor)); Assert.IsType <InstanceDescriptor>(converted); Assert.Equal(new object[] { 1, 2, 3, 4 }, ((InstanceDescriptor)converted).Arguments); Assert.Throws <NotSupportedException>(() => mc.ConvertTo(context, culture, new object(), typeof(object))); Assert.Throws <NotSupportedException>(() => mc.ConvertTo(context, culture, 12, typeof(int))); Assert.Throws <NotSupportedException>(() => mc.ConvertTo(context, culture, guid, typeof(Guid))); Assert.Equal(string.Empty, (string)mc.ConvertTo(null, typeof(string))); Assert.Equal(string.Empty, (string)mc.ConvertTo(context, CultureInfo.CreateSpecificCulture("ru-RU"), null, typeof(string))); } }
/// <summary> /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be /// used as generic method and casting is not required. /// <example> /// marginsconverter.ConvertTo<int>(context, culture, value); /// </example> /// </summary> public static T ConvertTo <T>(this MarginsConverter marginsconverter, System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, Object value) { if (marginsconverter == null) { throw new ArgumentNullException("marginsconverter"); } return((T)marginsconverter.ConvertTo(context, culture, value, typeof(T))); }
/// <summary> /// Extends ConvertTo so that methods that return a specific type object given a Type parameter can be /// used as generic method and casting is not required. /// <example> /// typeconverter.ConvertTo<int>(value); /// </example> /// </summary> public static T ConvertTo <T>(this MarginsConverter typeconverter, Object value) { if (typeconverter == null) { throw new ArgumentNullException("typeconverter"); } return((T)typeconverter.ConvertTo(value, typeof(T))); }