C# 动态类型转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/648195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:41:18  来源:igfitidea点击:

C# dynamic type conversions

c#

提问by Adi Barda

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 into A. Any suggestions? Thanks, Adi Barda

我们有 2 个对象 A 和 B:A 是 system.string,B 是一些 .net 原始类型(string、int 等)。我们想编写通用代码将 B 的转换(解析)值分配给 A。有什么建议吗?谢谢,阿迪巴尔达

采纳答案by Marc Gravell

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 IConvertibleetc, 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)));

回答by Tamas Czinege

What's wrong with the already existing System.Convertclass and the IConvertibleinterface?

已经存在的System.Convert类和IConvertible接口有什么问题?

回答by driis

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.

如前所述,System.Convert 和 IConvertible 将是第一个赌注。如果由于某种原因您不能使用这些(例如,如果内置类型的默认系统转换不适合您),一种方法是创建一个字典来保存每个转换的委托,并在其中进行查找在需要时找到正确的转换。

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.

显然,您可能希望在自定义转换例程中做一些更有趣的事情,但它证明了这一点。

回答by Vladislav Kostenko

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

MSDN有类型转换概述,您可以其中获得有关该主题的更多信息。我发现它很有用。