【问题标题】:Setting a non-static variable in separate static method在单独的静态方法中设置非静态变量
【发布时间】: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。但是,现在变量不再是静态的,我不能这样做。

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

  1. 为什么将endpoints 更改为MethodThatAddsToDictionary() 会更改_endpoints?我假设是因为它是一个非静态变量。
  2. 为什么这对_token 不一样?

这些问题似乎是按值传递和按引用传递之间的细微差别,但我不确定我在这里缺少什么。现在我只是将令牌变量保存到返回的 Dictionary 并在方法调用后将变量设置在 Page_Load 中。

谢谢!

【问题讨论】:

标签: c# asp.net


【解决方案1】:

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

因为您将_endpoints 传递给函数,而Dictionary 是一个引用类型,所以endpoints 是对与_endpoints 相同的字典的引用。

为什么这对 _token 不一样?

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

这些问题似乎是按值传递和按引用传递之间的细微差别

有点。 所有参数都是“按值”传递的,但是对于引用类型(如Dictionary),值对对象的引用。如果您在参数类型之前使用ref 关键字,可以token 执行类似的操作,这通过引用传递字符串。

【讨论】:

  • 不要认为string 是一种值类型.. 但它的行为就像一个(顺便说一句,我没有投反对票)
  • String 是一个引用类型。它的行为与引用类型完全一样,而不是值类型。作为一个值类型(对于实际上值类型的东西)不一定是不可变的。值类型和引用类型都可以是不可变的;引用类型和值类型都可以是可变的。
  • @BackDoorNoBaby 我恳求暂时的精神错乱。固定。
  • 有趣 - 我认为这与我实例化 Dictionary 并没有为 string 做同样的事情有关,这使得它们根本不同。这很有意义,感谢您的解释!
猜你喜欢
  • 1970-01-01
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 2015-02-18
  • 2019-03-10
相关资源
最近更新 更多