在单独的静态方法中设置非静态变量

时间:2017-03-10 18:55:54

标签: c# asp.net

这个问题是我之前提到的一个问题的扩展,链接documentation

从那时起,我已将我的应用程序更改为不使用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。但是,现在变量不再是静态的,我不能这样做。

我想这个设置有两个基本问题:

  1. 为什么更改endpoints中的MethodThatAddsToDictionary()会更改_endpoints?我假设因为它是一个非静态变量。
  2. 为什么_token的效果不一样?
  3. 这些问题似乎是传递价值和传递参考之间的细微差别,但我不确定我在这里缺少什么。现在,我只是将令牌变量保存到返回的Dictionary,并在方法调用后在Page_Load中设置变量。

    谢谢!

1 个答案:

答案 0 :(得分:2)

  

为什么更改MethodThatAddsToDictionary()中的端点会更改_endpoints

由于您已将_endpoints传递给该函数,并且Dictionary是引用类型,因此endpoints是对_endpoints相同字典的引用。

  

为什么这对_token不起作用?

string 也是引用类型,但您并未更改其引用的值,您将引用设置为指向一个 new 字符串值,它对原始值没有影响。

  

这些问题似乎是传递价值和传递参考之间的细微差别

排序。 所有参数都按值#34;传递,但对于参考类型(如Dictionary),值对宾语。如果您在参数类型之前使用token关键字,通过引用传递字符串,可以执行与ref类似的操作。

相关问题