예제 #1
0
        // official doc
        // introduced all converting method of c#
        // https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/type-conversion

        // convert table
        //https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/conversion-tables

        public static void Play()
        {
            //NOTE kind of raw way of convert
            object a = Convert.ChangeType("123", typeof(int));

            //NOTE TypeConverter more raw convert
            var vodkaConverter = TypeDescriptor.GetConverter(typeof(Vodka));
            var toString       = vodkaConverter.CanConvertTo(typeof(string));
            var fromString     = vodkaConverter.CanConvertFrom(typeof(string));

            Console.WriteLine(vodkaConverter.IsValid(5));
            Console.WriteLine(toString);
            Console.WriteLine(fromString);

            Console.WriteLine(vodkaConverter.ConvertFrom("yuyi"));
            Console.WriteLine(vodkaConverter.ConvertFrom(99));

            var vodka = new Vodka()
            {
                Degree = 70, Brand = "life", Type = "drink"
            };

            Console.WriteLine(vodka);
            Console.WriteLine(vodkaConverter.ConvertToString(vodka));

            foreach (Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues())
            {
                Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c));
            }

            var d = Convert.ChangeType(vodka, typeof(string));
        }
예제 #2
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string vs)
            {
                var v = new Vodka();
                v.Brand = vs;
                return(v);
            }

            if (value is int vi)
            {
                var v = new Vodka();
                v.Degree = vi;
                return(v);
            }

            return(base.ConvertFrom(context, culture, value));
        }