首页 新闻 会员 周边

全局变量的问题(迷惑了)。

0
悬赏园豆:20 [已解决问题] 解决于 2010-07-06 18:45

今天看泛型的时候,遇到这样的一个问题。

 调用一次 Copy(lst1, lst2);

页面输出lst2.Count为2;

而调用changestr(a, b);页面输出还是222。

代码如下 :

代码
public List<int> lst1 = new List<int>();
public List<int> lst2 = new List<int>();
public string a = "111";
public string b = "222";
protected void Page_Load(object sender, EventArgs e)
{


lst1.Add(
2);
lst1.Add(
4);

Response.Write(lst2.Count);
//输出0
Copy(lst1, lst2);
Response.Write(lst2.Count);
//输出2


changestr(a, b);
Response.Write(b);
//输出222
}

public static void Copy<T>(List<T> source, List<T> destination)
{
foreach (T obj in source)
{
destination.Add(obj);
}
}
public static void changestr(string a1, string b1)
{
b1
= a1;
}

 

 

clound的主页 clound | 菜鸟二级 | 园豆:481
提问于:2010-07-03 12:57
< >
分享
最佳答案
0

changestr(ref a, ref b);
Response.Write(b);

public static void changestr(ref string a1,ref string b1)
{
b1
= a1;
}

 

收获园豆:20
dudu | 高人七级 |园豆:31003 | 2010-07-03 13:57
我想知道为什么 执行Copy(lst1, lst2); 而输出的值为2。 lst2 是个全局变量,而 Copy<T> 方法中 并为对 lst2进行重新赋值。
clound | 园豆:481 (菜鸟二级) | 2010-07-03 14:27
再执行一次Copy(lst1, lst2); lst2.Count就变成4了。
clound | 园豆:481 (菜鸟二级) | 2010-07-03 14:27
@clound:请参考http://msdn.microsoft.com/zh-cn/library/s6938f28(VS.80).aspx
dudu | 园豆:31003 (高人七级) | 2010-07-03 14:52
@dudu:非常谢谢,提供的参考。是我没弄懂值类型与引用类型的区别。明白了大概,不过还有个疑问,既然string 是个引用类型,那么 Response.Write(b);//输出是不是也应该为111才对呢?
clound | 园豆:481 (菜鸟二级) | 2010-07-05 20:42
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册