【发布时间】:2017-03-11 03:08:04
【问题描述】:
这个问题是我之前提出的问题的扩展,链接here。
从那时起,我已将我的应用程序更改为不使用 static 全局变量来存储 API 端点信息。我没有提到的是,除了Dictionary 之外,我还设置了令牌变量。我的代码现在看起来像这样:
public partial class TestControl : UserControl
{
private string _token = null; //this used to be a static variable
protected Dictionary<string, string> _endpoints = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
//clear the lists of endpoints each time the page is loaded
_endpoints.Clear();
...
var sessionInfo = MethodThatAddsToDictionary(_endpoints, _token);
//logic that sets the global tokens based on return values
...
}
public static Dictionary<string, string> MethodThatAddsToDictionary(Dictionary<string, string> endpoints, string token)
{
var returnedTokens = new Dictionary<string, string>();
token = "returned_token"; //this doesn't set the global _token value
...
endpoints.Add(response.First(), response.Last());
}
}
在MethodThatAddsToDictionary() 中,我直接从方法中设置了“全局”变量_token。但是,现在变量不再是静态的,我不能这样做。
我想我对这个设置有两个基本问题:
- 为什么将
endpoints更改为MethodThatAddsToDictionary()会更改_endpoints?我假设是因为它是一个非静态变量。 - 为什么这对
_token不一样?
这些问题似乎是按值传递和按引用传递之间的细微差别,但我不确定我在这里缺少什么。现在我只是将令牌变量保存到返回的 Dictionary 并在方法调用后将变量设置在 Page_Load 中。
谢谢!
【问题讨论】:
-
嗨,我的问题是;为什么需要全局变量?您是否考虑过 Session 变量? msdn.microsoft.com/en-us/library/ms178581.aspx?或应用变量:msdn.microsoft.com/en-us/library/94xkskdf.aspx