对象作为参数传递给另一个类,按值或引用? [英] Object passed as parameter to another class, by value or reference?

查看:153
本文介绍了对象作为参数传递给另一个类,按值或引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我知道,在默认情况下,传递给函数的任何参数是通过复制,这就是,在函数内部,有参数的本地副本。但是,当一个对象被当作参数传递到另一个类传递什么?

In C#, I know that by default, any parameters passed into a function would be by copy, that's, within the function, there is a local copy of the parameter. But, what about when an object is passed as parameter to another class?

希望接踵而来引用或按值传递的场景:

Would a scenario like the following one be passed by reference or by value:

class MyClass {
   private Object localObj;

   public void SetObject(Object obj) {
      localObj = obj;
   }
}

void Main() {
   Object someTestObj = new Object();
   someTestObj.name = "My Name";
   MyClass cls = New MyClass();
   cls.SetObject(someTesetObj);
}

在这种情况下,将类变量 localObj 是具有同一副本的 someTestObj 驱动类产生的?或者将两个变量是指向一个不同的对象实例?

In this case, would the class variable localObj be having the same copy as the someTestObj created in the Main driver class? Or would the two variables be pointing to a different object instance?

推荐答案

对象将参照不管的同一方法中传递类或者其他类。下面是相同的示例代码修改后的版本,以帮助你理解。该值将变为

Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Employee
    {
        public string Name { get; set; }
    }

    class MyClass
    {
        public Employee EmpObj;

        public void SetObject(Employee obj)
        {
            EmpObj = obj;
        }
    }

    public class Program
    {
       static void Main(string[] args)
        {
            Employee someTestObj = new Employee();
            someTestObj.Name = "ABC";

            MyClass cls = new MyClass();
            cls.SetObject(someTestObj);
            // 
            Console.WriteLine("Changing Emp Name To xyz");
            someTestObj.Name = "xyz";
           //
            Console.WriteLine("Accessing Assigned Emp Name");
            Console.WriteLine(cls.EmpObj.Name); 

           Console.ReadLine();
       }       
    }



}

}

这篇关于对象作为参数传递给另一个类,按值或引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆