C#Static的使用导致System.StackOverflowException
在C#中定义Static函数,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StaticTest
{
class Test
{
static int count = 0;
public static int Sum(int a, int b)
{
count++;
Console.WriteLine(count);
return Sum(a, b);
}
}
class Program
{
static void Main(string[] args)
{
int c = Test.Sum(1, 2);
Console.ReadLine();
}
}
}
结论
程序会一直循环调用Sum,知道报出System.StackOverflowException错误,即待定的方法调用太多,导致执行堆栈溢出。
本文介绍了一个C#中Static函数循环调用的例子,展示如何因递归调用导致System.StackOverflowException错误。通过该例子,读者可以了解静态成员变量和方法在递归调用时可能出现的问题。
2329

被折叠的 条评论
为什么被折叠?



