2015-12-18 84 views
2

我是一个新的程序员在这里。我有以下代码。我通过价值传递了对象,但是当我打印结果时,我得到了这个效果。困惑于通过引用传递和按值传递#

兽人当前生命值为80

精灵攻击兽人造成20点伤害!

当前健康的兽人是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); 
     } 
    } 
} 
+0

这不是很清楚什么迷惑你,在进攻方法兽人健康的损害,然后你又把它打印在主 –

+0

如果你感到困惑,为什么不只是做一个C#MSDN谷歌搜索'ref与价值' – MethodMan

回答

2

在C#/。NET中,对象是按引用还是按值传递是由对象的类型决定的。如果该对象是一个引用类型(即它是用class声明的),它通过引用传递。如果对象是一个值类型(即它是用struct声明的),则它是按值传递的。

如果你改变敌人的声明

struct Enemy 

你会看到传递值语义。

1

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

这里,关于这个问题的更多信息,SA链接:http://jonskeet.uk/csharp/parameters.html