如何在运行时转换类型?

发布于 2024-07-09 22:47:13 字数 554 浏览 7 评论 0原文

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

这很容易:

string valueToConvertFrom = "123";

int blah = Convert.ToInt32(valueToConvertFrom);

但是...我不知道(直到运行时)我需要转换的值to 是一个“Int”(或其他)。 我已经尝试过:

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

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

但这给了我以下错误:“对象必须实现 IConvertible。”

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

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.

This would be easy:

string valueToConvertFrom = "123";

int blah = Convert.ToInt32(valueToConvertFrom);

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

静若繁花 2024-07-16 22:47:13

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

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

TypeConverter tc =  TypeDescriptor.GetConverter(convertToType);             

object blah =tc.ConvertFromString(valueToConvertFrom);

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);
糖果控 2024-07-16 22:47:13

String 类实现了 IConvertible,这段代码应该可以工作。 您的目标是哪个版本的 .NET?

object o = Convert.ChangeType( str, convertToType );

此外,您提到的大多数类型都实现 Parse 方法,因此您最好的选择可能是这样的。

Type convertToType = ...;
MethodInfo mi = convertToType.GetMethod("Parse", BindingFlags.Static);
object blah;
if(mi != null)
{
    blah = mi.Invoke(null, new object[]{valueToConvertFrom});
}
else
{
    // the type doesn't implement the Parse method, handle it another way :/
}

String class implements IConvertible, this code simply SHOULD work. Which version of .NET are you aiming?

object o = Convert.ChangeType( str, convertToType );

Besides, most of the types you mentioned implement Parse method, so your best shot might be something like this.

Type convertToType = ...;
MethodInfo mi = convertToType.GetMethod("Parse", BindingFlags.Static);
object blah;
if(mi != null)
{
    blah = mi.Invoke(null, new object[]{valueToConvertFrom});
}
else
{
    // the type doesn't implement the Parse method, handle it another way :/
}
想你只要分分秒秒 2024-07-16 22:47:13

Timothy 的问题,通常应用于 .NET 中的类型转换问题,是一个非常大的问题。 虽然转换策略在已知类型的特定场景中有些简单,但不幸的是,在 .NET 的任何实现中都没有通用策略来完成运行时从一种任意类型到另一种类型的类型转换,Redmond 也没有提供这样的策略。 但是,Microsoft 为类型转换的一般概念提供了一些很好的指南,包括:

I我必须在我的系统中处理相同的一般问题,作为一种解决方案,我将所有标准策略合并为一种方法。 这个问题的范围很广,相关的转换策略也多种多样,因此这种综合方法只能在一篇完整的技术文章中涵盖。 不过,我在这里提供了我的方法文档的副本,希望这能帮助您牢牢掌握如果您想开发类似的通用解决方案则需要满足的总体要求。 这是我的文档的链接:

我希望这对您有所帮助,

马克

Timothy's question, as applied generally to the question of Type conversion in .NET, is a very big issue. While conversion strategies are somewhat straightforward in specific scenarios with known types, unfortunately there is no generalized strategy in any implementation of .NET to accomplish Type conversion at run-time from one arbitrary Type to another, nor is such a strategy forthcoming from Redmond. However, Microsoft supplies some good guidelines for the general concept of Type conversion, including:

I have had to deal with the same general issue in my systems, and as a solution I have consolidated all the standard strategies into one method. The scope of this issue is broad and the related conversion strategies are varied, so this consolidated approach can only be covered in a complete technical article. However, I offer here a copy of my method documentation in hopes this will help you get a firm grasp on the overall requirements you will need to address if you want to develop a similar, generalized solution. Here's the link to my documentation:

I hope this helps you out,

Mark

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文