gpt4 book ai didi

c# - 在 C# 中转换对象类型

转载 作者:太空狗 更新时间:2023-10-29 20:03:47 24 4
gpt4 key购买 nike

我今天遇到了一个问题,我不完全确定它为什么不起作用。

以下代码示例将崩溃:

static void Main(string[] args)
{
int i32 = 10;
object obj = i32;
long i64 = (long)obj;
}

这将导致 InvalidCastException。为什么这不起作用?难道 C# 不够聪明,不知道对象实际上是 int 类型吗?

我已经想出了一个解决方法,但我很好奇为什么上面的代码示例一开始就不起作用。

谢谢,蒂姆

最佳答案

没有从盒装 Int32 到 Int64 的转换可用。对 int 进行中间转换应该可行,因为编译器愿意生成:

// verify obj is a boxed int, unbox it, and perform the *statically*
// known steps necessary to convert an int to a long
long i64 = (long) ((int)obj);

但不是(假设)这个:

// Find out what type obj *actually* is at run-time and perform 
// the-known-only-at-run-time steps necessary to produce
// a long from it, involving *type-specific* IL instructions
long i64 = (long)obj;

这是一个 blog post由埃里克·利珀特 (Eric Lippert) 撰写。

关于c# - 在 C# 中转换对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3915217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com