在C#中避免嵌套方法调用

时间:2014-08-07 08:00:28

标签: c#

我正在运行一个代码,其中有太多嵌套方法调用。运行它,给出一个

  

堆栈溢出异常

由于嵌套方法调用也可能。 我怎么能把它删除?

这是代码示例

public void searchProc(string path, string cPattern, string oPattern)
{
    var sqlFiles = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories);
    string sqlObject = null;
    string content;


    Console.WriteLine("\nThe {0} TABLE is used in the following procedures :", oPattern);
    int cnt = 0;
    foreach (string currentFile in sqlFiles)
    {
        content = File.ReadAllText(currentFile);
        //      Console.WriteLine(currentFile);

        // condition checks whether the table that exists in a file is actually contained in the procedure
        if (Regex.IsMatch(content, oPattern, RegexOptions.IgnoreCase) && Regex.IsMatch(content, cPattern, RegexOptions.IgnoreCase))
        {
            cnt++;
            Match match = Regex.Match(content, cPattern, RegexOptions.IgnoreCase);
            sqlObject = match.Groups["proc_name"].Value;

            string[] split = sqlObject.Split('.');
            sqlObject = split[split.Count() - 1];

            sqlObject = sqlObject.Trim(charToTrim);
            using (StreamWriter sw = System.IO.File.AppendText(writePath))
            {
                sw.WriteLine(sqlObject);
            }

            searchProcInProc(path, cPattern, sqlObject);
        }
    }

    Console.WriteLine("Number of hits are : {0}", cnt);
}

public void searchProcInProc(string path, string cPattern, string oPattern)
{

    nestProc = new List<string>();
    sqlConnection.Open();
    cmd = new SqlCommand("SELECT CHILDPROC FROM PROC_DEPENDENCY_1_TBL WHERE PARENTPROC LIKE '%" + oPattern + "%'", sqlConnection);

    sqlReader = cmd.ExecuteReader();
    int cnt = 0;
    while (sqlReader.Read())
    {
        cnt++;
        nestProc.Add(sqlReader.GetString(0));
    }
   // Console.WriteLine("\n" + cnt);

    foreach (string s in nestProc)
    {
        using (StreamWriter sw = System.IO.File.AppendText(writePath))
        {
            sw.WriteLine("EXECUTED PROC " + s);
        }


    }
    string[] split;
    string temp;

    sqlConnection.Close();
    foreach (string s in nestProc)
    {
        temp = s;
        split = temp.Split('.');
        temp = split[split.Count() - 1];

        temp = s.Trim(charToTrim);
        searchProcInProc(path, cPattern, temp);
    }
}

一次又一次地调用SearchProcIn Proc方法......输出包含多个数千行

1 个答案:

答案 0 :(得分:2)

您可以使用此.NET函数:

RuntimeHelpers.EnsureSufficientExecutionStack();

但我认为你应该重构你的代码以避免递归。