예제 #1
0
        public void TestGeneralTimeSpanConversion()
        {
            var converter = new TimeSpanConverter();

            Assert.Null(converter.ConvertFromString("", CULTURE, typeof(TimeSpan?)));
            Assert.Throws <FormatException>(() => converter.ConvertFromString("", CULTURE, typeof(TimeSpan)));
            Assert.AreEqual(new TimeSpan(1, 2, 3, 4), converter.ConvertFromString("01:02:03:04", CULTURE, typeof(TimeSpan)));
            Assert.AreEqual(new TimeSpan(2, 3, 4), converter.ConvertFromString("02:03:04", CULTURE, typeof(TimeSpan)));
        }
예제 #2
0
        public void TestTimespanConversionWithFormat()
        {
            var converter = new TimeSpanConverter(@"hh\-mm\-ss");

            Assert.AreEqual(new TimeSpan(3, 15, 22), converter.ConvertFromString("03-15-22", CULTURE, typeof(TimeSpan)));

            converter = new TimeSpanConverter(@"hh'h 'mm'm 'ss's'");
            Assert.AreEqual(new TimeSpan(2, 12, 37), converter.ConvertFromString("02h 12m 37s", CULTURE, typeof(TimeSpan)));

            converter = new TimeSpanConverter(@"h'ч 'm'мин 's'сек'");
            Assert.AreEqual(new TimeSpan(2, 12, 8), converter.ConvertFromString("2ч 12мин 8сек", CULTURE, typeof(TimeSpan)));
        }
예제 #3
0
 /// <summary>
 /// Возвращает один из предустановленных конвертеров для преобразования значений типа <paramref name="type"/> из строк.
 /// </summary>
 /// <param name="type">Тип значения для преобразования.</param>
 /// <param name="format">Используемый формат преобразования. Если не задан, используется формат по умолчанию.</param>
 public static IConverter GetConverterForType(Type type, string format = "")
 {
     type = Nullable.GetUnderlyingType(type) ?? type;
     if (BooleanConverter.CanConvertTo(type))
     {
         return(new BooleanConverter());
     }
     if (TransparentConverter.CanConvertTo(type))
     {
         return(TransparentConverter.Instance);
     }
     if (NumberConverter.CanConvertTo(type))
     {
         return(new NumberConverter());
     }
     if (DecimalConverter.CanConvertTo(type))
     {
         return(new DecimalConverter());
     }
     if (TimeSpanConverter.CanConvertTo(type))
     {
         return(new TimeSpanConverter(format));
     }
     if (DateTimeConverter.CanConvertTo(type))
     {
         return(new DateTimeConverter(format));
     }
     if (EnumConverter.CanConvertTo(type))
     {
         return(new EnumConverter());
     }
     if (CollectionConverter.CanConvertFrom(type))
     {
         return(new CollectionConverter(GetConverterForType(CollectionConverter.GetElementType(type), format)));
     }
     throw new InvalidOperationException("failed to find suitable converter for type " + type);
 }