C# 为什么';我的元组返回值到程序主方法是否正确?

C# 为什么';我的元组返回值到程序主方法是否正确?,c#,tuples,C#,Tuples,我有一个方法,它应该将2个变量从类方法返回到main,但是我显然使用的元组是错误的,因为当我检查方法返回的内容时,元组是错误的 using System; namespace App1 { public class Player { public int Health = 100; public int Mana = 100; static Tuple<int, int> SetAttributes(int pHealth, in

我有一个方法,它应该将2个变量从类方法返回到main,但是我显然使用的元组是错误的,因为当我检查方法返回的内容时,元组是错误的

using System;

namespace App1
{
     public class Player
    {
        public int Health = 100;
        public int Mana = 100;

static Tuple<int, int> SetAttributes(int pHealth, int pMana)
            {

            pHealth++;
            pMana++;
            Console.WriteLine("Health: " + pHealth + " Mana: " + pMana);

            return new Tuple<int, int>(pHealth, pMana);
            }//method end

static void Main(string[] args)
        {



            Player myPlayer = new Player();
            SetAttributes(myPlayer.Health, myPlayer.Mana);
            Console.WriteLine("In Main ...Health: " + myPlayer.Health + " Mana: " + myPlayer.Mana);

        }

    } //class End 
}//Namespace end
使用系统;
名称空间App1
{
公开课选手
{
公共卫生=100;
公共智力法力=100;
静态元组集合属性(int-pHealth,int-pMana)
{
菲尔斯++;
pMana++;
控制台写入线(“生命:+pHealth+”法力:+pMana”);
返回新元组(pHealth,pMana);
}//方法端
静态void Main(字符串[]参数)
{
Player myPlayer=新玩家();
设置属性(myPlayer.Health,myPlayer.Mana);
控制台.WriteLine(“主…健康:+myPlayer.Health+”法力:+myPlayer.Mana”);
}
}//类结束
}//命名空间结束

SetAttributes
不通过引用获取其参数,并且您忽略了main方法中的返回值。因此,您将立即丢弃递增的值。

SetAttributes返回元组,因此其中只有更新的值

        static void Main(string[] args)
        {
            Player myPlayer = new Player();
            Tuple<int, int> newValues = SetAttributes(myPlayer.Health, myPlayer.Mana);
            myPlayer.Health = newValues.Item1;
            myPlayer.Mana = newValues.Item2;
            Console.WriteLine("In Main ...Health: " + myPlayer.Health + " Mana: " + myPlayer.Mana);
        }
static void Main(字符串[]args)
{
Player myPlayer=新玩家();
Tuple newValues=SetAttributes(myPlayer.Health,myPlayer.Mana);
myPlayer.Health=newValues.Item1;
myPlayer.Mana=newValues.Item2;
控制台.WriteLine(“主…健康:+myPlayer.Health+”法力:+myPlayer.Mana”);
}

在您的
main
方法中,您没有从
SetAttributes()读取元组。

这里有一个更新的
main
方法,供您读取元组值


static void Main(string[] args)
        {
            Player myPlayer = new Player();
            var tuple = SetAttributes(myPlayer.Health, myPlayer.Mana);
            Console.WriteLine("In Main ...Health: " + tuple.Item1 + " Mana: " + tuple.Item1);
        }

是元组的MSDN文档

只想补充一下, 您可以在Main方法中使用特定的名称,而不是使用Item1和Item2或其他项

(int health, int mana) = SetAttributes(myPlayer.Health, myPlayer.Mana);
// Use health and mana like you normally would.

这行不行,因为生命值和法力值是值类型

SetAttributes(myPlayer.Health, myPlayer.Mana);
这将起作用,因为您将获得返回值

Tuple<int, int> ret = SetAttributes(myPlayer.Health, myPlayer.Mana);
myPlayer.Health = ret.Item1;
myPlayer.Mana = ret.Item2;
Tuple ret=SetAttributes(myPlayer.Health,myPlayer.Mana);
myPlayer.Health=ret.Item1;
myPlayer.Mana=ret.Item2;

谢谢,这非常有效,我知道我需要做什么了。