C# dynamic type conversions

前端 未结 4 1719
别那么骄傲
别那么骄傲 2020-12-14 05:09

We have 2 objects A & B: A is system.string and B is some .net primitive type (string,int etc). we want to write generic code to assign the converted (parsed) value of B

相关标签:
4条回答
  • 2020-12-14 05:17

    There is an overview of type conversions at MSDN where you can get more info about the topic. I've found it useful.

    0 讨论(0)
  • 2020-12-14 05:21

    What's wrong with the already existing System.Convert class and the IConvertible interface?

    0 讨论(0)
  • 2020-12-14 05:24

    The most pragmatic and versatile way to do string conversions is with TypeConverter:

    public static T Parse<T>(string value)
    {
        // or ConvertFromInvariantString if you are doing serialization
        return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
    }
    

    More types have type-converters than implement IConvertible etc, and you can also add converters to new types - both at compile-time;

    [TypeConverter(typeof(MyCustomConverter))]
    class Foo {...}
    
    class MyCustomConverter : TypeConverter {
         // override ConvertFrom/ConvertTo 
    }
    

    and also at runtime if you need (for types you don't own):

    TypeDescriptor.AddAttributes(typeof(Bar),
        new TypeConverterAttribute(typeof(MyCustomConverter)));
    
    0 讨论(0)
  • 2020-12-14 05:35

    As already mentioned, System.Convert and IConvertible would be the first bet. If for some reason you cannot use those (for instance, if the default system conversions for the built in types is not adequate for you), one approach is to create a dictionary that holds delegates to each conversion, and make a lookup in that to find the correct conversion when needed.

    For instance; when you want to convert from String to type X you could have the following:

    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(SimpleConvert.To<double>("5.6"));
            Console.WriteLine(SimpleConvert.To<decimal>("42"));
        }
    }
    
    public static class SimpleConvert
    {
        public static T To<T>(string value)
        {
            Type target = typeof (T);
            if (dicConversions.ContainsKey(target))
                return (T) dicConversions[target](value);
    
            throw new NotSupportedException("The specified type is not supported");
        }
    
        private static readonly Dictionary<Type, Func<string, object>> dicConversions = new Dictionary <Type, Func<string, object>> {
            { typeof (Decimal), v => Convert.ToDecimal(v) },
            { typeof (double), v => Convert.ToDouble( v) } };
    }
    

    Obviously, you would probably want to do something more interesting in your custom conversion routines, but it demonstrates the point.

    0 讨论(0)
提交回复
热议问题