gpt4 book ai didi

c# - 奇怪的 StackOverflow 异常

转载 作者:行者123 更新时间:2023-11-30 19:08:34 25 4
gpt4 key购买 nike

我有以下代码:

class Program
{
static void Main(string[] args)
{
Console.WriteLine((Program)3);

Console.WriteLine("Execution complete.");
Console.Read();
}

public static implicit operator Program(int asd)
{ return 10; }
}

在最后一行抛出 StackOverflow 异常 ({ return 10; })。我不明白为什么,因为堆栈上应该有足够的空间容纳所有内容。

我正在学习 operator 关键字和隐式/显式转换,所以我做了这个小例子来测试一些东西。

最佳答案

堆栈溢出是由于这个方法无限调用自己造成的:

public static implicit operator Program(int asd)
{ return 10; }

为什么这个方法会无限调用自己?嗯,这个方法定义了一个从 intProgram 的隐式转换,所以你应该返回一个 Program 的实例给定一个 int 调用了 asd。但是,您返回一个 int。通常,这会失败,但由于您定义了从 intProgram 的隐式转换,编译器会“好的,没问题”。

但在运行时,它会尝试将您的 10 转换为 Program再次调用隐式转换方法。隐式转换方法返回一个 10,运行时试图再次将其隐式转换为 Program,因此它再次调用该方法...

我真的不明白你在这里想做什么,所以我不知道这个问题的解决方案是什么。

关于c# - 奇怪的 StackOverflow 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205607/

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