How Can I Convert Types at Runtime?(如何在运行时转换类型?)
问题描述
我的场景应该很简单...我要转换的类型 FROM 是 ALWAYS '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);
这篇关于如何在运行时转换类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在运行时转换类型?


- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 使用 rss + c# 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01