开发者

Fundamental question about boxing / c#

Is it possible to change the value stored inside bar after it has been added?

I have tried 'boxing' the string foo but it doesnt work.

string foo = "aaaaaaa";
var bar = new System.Web.UI.HtmlControls.HtmlGenericControl("div") { InnerHtml =foo };
foo = "zzzzz开发者_JAVA百科z";
plcBody.Controls.Add(bar);//want this to contain 'zzzzzz'


To do that you have to set the value, like this:

string foo = "aaaaaaa";
var bar = new System.Web.UI.HtmlControls.HtmlGenericControl("div") { InnerHtml = foo };
bar.InnerHtml = "zzzzzz";
plcBody.Controls.Add(bar);

Strings themselves are immutable (in .NET at least, this isn't universally true), you can't change it after it's been passed...you passed the value of the variable, which is a string reference - you haven't passed a reference to the original variable, so changing the original variable to refer to a different string doesn't do anything. When you change the variable, you're changing which string foo refers to, not editing its original string, as that's immutable.

If it's easier to think of, you're passing "what foo means" not "foo itself", so once that string goes into whatever you're passing it into, it has no relation to the original variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜