C#重新加载时静态方法重置字段
我有一个按顺序显示颜色的类C#重新加载时静态方法重置字段,c#,static-methods,C#,Static Methods,我有一个按顺序显示颜色的类 public class Color { private static string[] _colors = {"Red", "Green", "Blue"}; public static int Index { get; set; } public static string GetNextColor() { var retVal = _colors[Index]; Index++;
public class Color
{
private static string[] _colors = {"Red", "Green", "Blue"};
public static int Index { get; set; }
public static string GetNextColor()
{
var retVal = _colors[Index];
Index++;
return retVal;
}
}
我通过以下代码使用上述类:
[HttpGet]
public string TestColor()
{
Color.Index = 0;
return string.Format("First color: {0} Second color: {1} Third color: {2}", Color.GetNextColor(), Color.GetNextColor(), Color.GetNextColor());
}
哪个显示这个结果
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
First color: Red Second color: Green Third color: Blue
</string>
第一种颜色:红色第二种颜色:绿色第三种颜色:蓝色
现在我的问题是
如何在每次重新加载页面时将索引重置为0,而不将其重置为Color.Index=0代码>
据我所知,静态字段只能通过应用程序重启来重置,因此在我的应用程序中,每次调用此静态方法时,我总是被迫将索引重置为0。我只想在每次重新加载页面时将此字段“Index”重置为0。我不确定是否可以避免为我的代码的每个顶部设置Color.Index=0
。如果您想要一个随每个页面请求重置的变量,应该将其设置为成员变量,而不是静态变量。对于每个HTTP请求,视图、控制器、模型和管道对象都会被分解并重新创建,因此它会自动重置颜色
如果您坚持使用静态变量执行此操作,您可以添加一行代码将其设置为0。除了自行设置之外,没有其他方法可以执行此操作。您可以通过更改索引++,确保索引
值永不溢出代码>到索引=(索引+1)%\u colors.Length代码>我对将其作为成员变量很感兴趣,但是我可以在静态方法中访问成员变量吗?你有样本吗,谢谢为什么它必须是一个静态方法?因为我需要在不同的方法中使用它。你答案的第一部分是不正确的。您无法完全确定HTTP请求是否创建此类的新实例并重置非静态变量。它取决于API(或DI)配置,请求生存期范围只是众多选项中的一个。