如何在运行时转换类型?

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

问题描述

我的场景应该很简单...我要转换的类型 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);

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
quot;Overflowquot; compiler error with -9223372036854775808L(编译器错误-9223372036854775808L(Q;溢出Q))
Visual Studio 2010 ReportViewer Assembly References(Visual Studio 2010 ReportViewer程序集引用)
Weird behaviour when I open a reportviewer in WPF(在WPF中打开报表查看器时出现奇怪的行为)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)