如何在运行时转换类型? [英] How Can I Convert Types at Runtime?

查看:45
本文介绍了如何在运行时转换类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的场景应该很简单...我要转换的类型 FROMALWAYS 'string'.我想转换成... 可能是很多东西 - 整数、日期时间、... 字符串等.

My scenario should be simple... the type I want to convert FROM is ALWAYS 'string'. What I want to convert to... could be many things - ints, DateTimes, ... strings, etc.

这很容易:

string valueToConvertFrom = "123";

int blah = Convert.ToInt32(valueToConvertFrom);

但是...我不知道(直到运行时)我需要转换为的值是Int"(或其他).我试过这个:

However... I don't know (until runtime) that the value I need to convert to is an 'Int' (or whatever). I have tried this:

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

object blah = Convert.ChangeType(valueToConvertFrom, convertToType);

但这给了我以下错误:对象必须实现 IConvertible."

But that gives me the following error: "Object must implement IConvertible."

我不想执行 switch 语句并根据类型名称调用Convert.ToBlah"...有什么建议吗?

I don't want to have to do a switch statement and call "Convert.ToBlah" based on the type name... any suggestions?

推荐答案

干净的方法是使用 TypeConverter.您可以通过调用 TypeDescriptor 来获取类型转换器的实例.GetConverter 然后使用类型转换器的实例进行转换.所以是这样的:

the clean way to do it is using the a TypeConverter. you can get an instance of a type converter by calling the TypeDescriptor.GetConverter and then using the instance of the type converter to do the convertion. so something like this:

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

TypeConverter tc =  TypeDescriptor.GetConverter(convertToType);             

object blah =tc.ConvertFromString(valueToConvertFrom);

这篇关于如何在运行时转换类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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