C#动态类型转换 [英] C# dynamic type conversions

查看:140
本文介绍了C#动态类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有2个对象A& B:A是system.string,B是.net基本类型(string,int等)。我们要编写通用代码,以将B的转换(解析)值分配给A。有什么建议吗?谢谢,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

推荐答案

进行字符串转换的最实用,最灵活的方法是使用 TypeConverter

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

更多类型具有类型转换器,而不是实现 IConvertible 等,您还可以在转换时将转换器添加到新类型;

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

这篇关于C#动态类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆