c#仅复制变量的整数值

c#仅复制变量的整数值,c#,C#,对不起,这个问题我忘了上c#的课,请耐心听我说。我有这个密码 public class TestClass { int indexcounter = 3; public int returnInteger() { int temporarystorage = indexcounter; indexcounter --; return temporarystorage; } } I indexcoun

对不起,这个问题我忘了上c#的课,请耐心听我说。我有这个密码

public class TestClass
{
     int indexcounter = 3;

     public int returnInteger()
     {
         int temporarystorage = indexcounter;
         indexcounter --;
         return temporarystorage;
     }
}

I indexcounter的第一个存储值为临时存储,即3。所以我可以返回临时存储值,即3。但它返回的值为2。这里发生了什么

好吧,您的代码的工作原理与您描述的一样

顺便说一句,
returnInteger
方法代码可以简化为
returnindexcounter---有关详细信息,请参阅

下面是一个快速演示:

public class TestClass
{
    int indexcounter = 3;

    public int returnInteger()
    {
        int temporarystorage = indexcounter;
        indexcounter --;
        return temporarystorage;
    }

    // I've added that property so that we can inspect the value of indexcounter outside this class
    public int IndexCounter {get {return indexcounter;} }

}

public class Program
{
    public static void Main(string[] args)
    {
        var a = new TestClass();

        Console.WriteLine(a.IndexCounter); // prints 3

        Console.WriteLine(a.returnInteger()); // prints 3

        Console.WriteLine(a.IndexCounter); // prints 2

        Console.WriteLine(a.returnInteger()); // prints 2

        Console.WriteLine(a.IndexCounter); // prints 1
    }
}

定义“不工作”-因为该代码应该工作。你的测试代码是什么?(请注意,一个更简单的实现是
返回indexcounter--
,它将在递减之前返回
indexcounter
的值。)“但这不起作用”我想这应该是指:“没有按预期工作”,所以请告诉我们您的预期。这里有一个典型的引用调用和值调用示例。您如何使用returnInteger()方法返回的值?如果您添加调用该类的代码,向我们展示如何从上面的代码中看到不可能的结果,根据上面的@Steve的观点,我们相信,无论您遇到什么样的错误,都不是源于您向我们展示的代码,而是源于调用您的函数的代码(您的开场白中没有包含该函数)。请包括所有代码-i;E调用
returnInteger()
的but。然后,我们将能够准确地指出问题所在。谢谢Zohar,也许我的代码中忘记了一些东西。:)事实上,我不是约翰,但我知道我们有相同的想法:-)