C# 如何防止这种循环?
当我调用这样的函数时,我不知道如何解决这个循环问题C# 如何防止这种循环?,c#,loops,C#,Loops,当我调用这样的函数时,我不知道如何解决这个循环问题 new Common.Utility.Parameter().Get(Common.Constants.Parameter.SomeParameter); 该错误可能是由调用参数的isHttpsCookie引起的。Get() 公用事业公司 public static class Utility { public class Parameter { public string Get(string key)
new Common.Utility.Parameter().Get(Common.Constants.Parameter.SomeParameter);
该错误可能是由调用参数的isHttpsCookie
引起的。Get()
公用事业公司
public static class Utility
{
public class Parameter
{
public string Get(string key)
{
string cookie = new Cookie().Read(key);
if (cookie == null)
{
var parameter = new Models.Parameter();
using (var db = new MyEntities())
parameter = db.Parameters.Where(w => w.Key == key).FirstOrDefault<Models.Parameter>();
if (parameter != null)
{
new Cookie().Write(key, parameter.Value);
return parameter.Value;
}
else
return string.Empty;
}
else
return cookie;
}
}
}
显然,您的代码陷入了一种您怀疑的递归。我遇到的问题是,为什么创建新对象只是为了调用单个方法。看起来您可以将它们作为类中的静态方法,因此不需要创建对象,因此不需要“循环”。仔细查看Cookie.Write()和Parameter.Get()方法,它们正在相互调用。当您声明
isHttpsCookie
时,调用Parameter.Get()
。在参数.Get()
中,如果条件有效,它将调用Cookie.Write()
。反过来,当您调用newcookie()
时,将再次调用isHttpsCookie
,并且它将永远继续
此代码的另一点:
if (isHttpsCookie)
isHttpCookie = false;
你是否试图说IshttpCookie在任何时候都应该是假的?那你为什么要申报呢
解决方案:像@Takeshi所说的那样:这些方法可以声明为静态的,因此不需要类声明就可以调用它们。您所怀疑的是正确的。IShttpCookie声明让你感到悲伤 当创建Cookie对象时,它会离开并执行从实用程序类获取的方法,该实用程序类创建Cookie实例。因此,你有你的递归 您需要更改初始化isHttpsCookie的方式。如果您正在写,可能只需初始化/检查。毕竟,你很可能会经常阅读而不是写作
希望有帮助。哪个循环?你到底有什么问题?当我调用“new Common.Utility.Parameter().Get(Common.Constants.Parameter.SomeParameter)”;“我收到以下错误“System.StackOverflowException”。可能的原因是cookie类调用参数函数,但我不知道如何解决这个问题!谢谢你和武石的建议。isHttpsCookie可以为真或假,具体取决于部署环境(如果生产环境是https)
if (isHttpsCookie)
isHttpCookie = false;