简体   繁体   English

C#动态类型转换

[英]C# dynamic type conversions

We have 2 objects A & B: A is system.string and B is some .net primitive type (string,int etc). 我们有2个对象A和B:A是system.string,B是.net原始类型(string,int等)。 we want to write generic code to assign the converted (parsed) value of B into A. Any suggestions? 我们想编写通用代码来将B的转换(解析)值分配给A.任何建议? Thanks, Adi Barda 谢谢,阿迪巴尔达

The most pragmatic and versatile way to do string conversions is with TypeConverter : 使用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; 更多类型具有类型转换器而不是实现IConvertible等,您还可以将转换器添加到新类型 - 在编译时;

[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)));

As already mentioned, System.Convert and IConvertible would be the first bet. 如前所述,System.Convert和IConvertible将是第一个赌注。 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: 当您想要从String转换为X类型时,您可以拥有以下内容:

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. 显然,您可能希望在自定义转换例程中做一些更有趣的事情,但它证明了这一点。

现有的System.Convert类和IConvertible接口出了什么问题?

There is an overview of type conversions at MSDN where you can get more info about the topic. MSDN有类型转换概述 ,您可以其中获得有关该主题的更多信息。 I've found it useful. 我发现它很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM