C#-为什么在通过方法放置此变量后不更改 [英] C# - Why is this variable not being changed after being put through a method

查看:35
本文介绍了C#-为什么在通过方法放置此变量后不更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我显然是编程新手,但正在尝试弄清为什么它不起作用

So I'm obviously fairly new to programming, but am trying to figure out why this isn't working

我正在尝试使用字符串myname,并将Mr.添加到它的开头.我知道我可以像myname = "Mr. " + myname一样简单地完成它,但是我试图了解如何使用方法来更改变量的值.那么,为什么不更改呢?

I'm trying to take the string myname, and add Mr. to the start of it. I know I could do it simply as just myname = "Mr. " + myname however I'm trying to understand how to use methods to change the values of variables. So, why doesn't this change?

public class Program
    {
        public static void Main(string[] args)
        {
            string myname = "harry";
            Console.WriteLine(myname); //output is harry

            namechanger(myname); //this should modify harry to Mr. Harry
            Console.WriteLine(myname); //output is still harry?
        }

        static string namechanger(string name) 
        {
            name = "Mr. " + name;
            return name;
        }

    }

推荐答案

字符串是不可变的按值传递.每次创建字符串时,它都永远不会更改.因此,与类实例不同,您无法通过将字符串交给修改它的方法来修改它.

Strings are immutable, and passed by value. Every time you create a string, it will never be changed. So unlike instances of classes, you cannot modify a string by handing it to a method which modifies it.

在这种情况下,由于您在namechangerreturn修改过的String,因此您要做的就是确保将myname分配给该方法的结果.像这样

In this case, since you return the modified String in namechanger, all you need to do is make sure you assign myname to the result of that method; like so

myname = namechanger(myname);

原始类型(intfloatlong等)以这种方式工作,struct实例也是如此-因此,如果您不确定为什么要使用将struct的值传递给方法时,其值不会改变.

Primitive types (int, float, long, etc) work this way, as do struct instances - so be sure to look for that in the future, if you're ever unsure why a struct's value is not changing when you pass it into a method.

这篇关于C#-为什么在通过方法放置此变量后不更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆