【问题标题】:C# Static methods and ConsoleC# 静态方法和控制台
【发布时间】:2011-06-27 14:36:33
【问题描述】:

嗨,我在一个类中有一个 static 方法,在我的控制台应用程序中,我像这样使用

Console.writeLine("Some thing Some thing");

Console.writeLine("Some thing Some thing");

String X=ClassName.Method(Para); <--- Check here


Console.writeLine("Some thing after some thing ");

Console.writeLine("Some thing after some thing ");

我的问题是在执行静态方法之后的代码在获得statc方法的返回值之后没有被执行,应用程序就像停止了..如何克服这个问题?

【问题讨论】:

  • 这不是正常行为。请给我们更多代码
  • “好像停止了”是什么意思?
  • 你尝试过 try/catch 还是调试和单步进入静态函数?
  • 不要向我们展示伪代码,而是向我们展示调用您的静态方法的真实代码以及静态方法本身。
  • String X=ClassName.Method(Para); 是做什么的?

标签: c# methods static console


【解决方案1】:

您的方法可能抛出异常或阻塞(不返回)。

要判断是否抛出异常,请在您的方法周围放置一个 try/catch 并在 catch 块中打印出任何异常。

try
{    
String X=ClassName.Method(Para); <--- Check here
}
catch (Exception e)
{
Console.WriteLine("{0}", e);
}

如果您的方法根本没有返回(例如,它可能在 Console.ReadLine 上被阻止),那么您需要在调试器中单步执行以查看原因。

此外,如果这是第一次访问“ClassName”类,您可能正在运行静态构造函数(“类型构造函数”)。有时,类型构造函数代码正在运行并不明显,但如果你正在做一些可能会在那里阻塞的事情,这也可能是你的问题,而不仅仅是“方法”方法。

【讨论】:

    【解决方案2】:

    暂停应用程序的问题在于ClassName.Method(Para) 调用,如果该方法阻塞了您的应用程序,您应该进一步查看那里。

    【讨论】:

      【解决方案3】:

      试试这个,看看调用函数内部是否发生了任何错误:

      Console.writeLine("Some thing Some thing");    
      Console.writeLine("Some thing Some thing");    
      
      try
      {    
      String X=ClassName.Method(Para); <--- Check here
      }    
      
      catch(Exception e)
      {
      Console.writeLine(e.Message);
      }
      
      Console.writeLine("Some thing after some thing ");    
      Console.writeLine("Some thing after some thing ");
      

      【讨论】:

        猜你喜欢
        • 2010-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 2012-10-11
        相关资源
        最近更新 更多