困惑关于通过引用传递和在c#中传递值

时间:2015-12-18 23:25:36

标签: c# reference pass-by-reference pass-by-value

我是这里的新程序员。我有以下代码。我按值传递了对象,但是当我打印结果时,我得到了这个

elf attacked orc for 20 damage!
Current Health for orc is 80
elf attacked orc for 20 damage!
Current Health for orc is 80

这让我对通过引用传递感到困惑,因为我没想到主要的健康状况是80,因为我按值传递了对象。有人可以解释程序主函数中的健康结果是80而不是100?

//MAIN class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace passingTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Enemy Objects
            Enemy elf = new Enemy("elf", 100, 1, 20);
            Enemy orc = new Enemy("orc", 100, 1, 20);
            elf.Attack(orc);
            Console.WriteLine("{0} attacked {1} for {2} damage!", elf.Nm, orc.Nm, elf.Wpn);
            Console.WriteLine("Current Health for {0} is {1}", orc.Nm, orc.Hlth);
            Console.ReadLine();

        }
    }
}

// Enemy Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace passingTest
{
    class Enemy
    {
        // variables
        string nm = "";
        int hlth = 0;
        int lvl = 0;
        int wpn = 0;

        public string Nm
        {
            get { return nm; }
            set { nm = value; }
        }
        public int Wpn
        {
            get { return wpn; }
            set { wpn = value; }
        }
        public int Hlth
        {
            get { return hlth; }
            set { hlth = value; }
        }
        public Enemy(string name, int health, int level, int weapon)
        {
            nm = name;
            hlth = health;
            lvl = level;
            wpn = weapon;
        }
        public void Attack(Enemy rival){
            rival.hlth -= this.wpn;
            Console.WriteLine("{0} attacked {1} for {2} damage!", this.nm, rival.nm, this.wpn);
            Console.WriteLine("Current Health for {0} is {1}", rival.nm, rival.hlth);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

在C#/ .NET中,对象是通过引用还是通过值传递,取决于对象的类型。如果对象是引用类型(即使用class声明它),则通过引用传递它。如果对象是值类型(即使用struct声明它),则按值传递。

如果您将Enemy的声明更改为

struct Enemy

你会看到按值传递的语义。

答案 1 :(得分:1)

在C#中,类被视为引用类型。引用类型是一种类型,其值为对适当数据的引用,而不是数据本身。例如,请考虑以下代码:

此处;链接包含有关主题的更多信息:http://jonskeet.uk/csharp/parameters.html