【问题标题】:confused about Passing by reference and passing by value in c#对c#中的引用传递和值传递感到困惑
【发布时间】:2016-03-25 17:49:32
【问题描述】:

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

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

这让我对按引用传递感到困惑,因为我没想到 main 中的运行状况为 80,因为我按值传递了对象。有人能解释一下程序 main 函数中的健康结果是 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);
        }
    }
}

【问题讨论】:

  • 不清楚是什么让你感到困惑,在攻击方法中兽人健康受损,然后你只需在主页面上再次打印它
  • 如果您感到困惑,为什么不在 ref vs value 上进行 C# MSDN google 搜索

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


【解决方案1】:

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

如果将 Enemy 的声明更改为

struct Enemy

您将看到按值传递的语义。

【讨论】:

    【解决方案2】:

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

    这里有一个链接,其中包含有关该主题的更多信息:http://jonskeet.uk/csharp/parameters.html

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多