码迷,mamicode.com
首页 > 其他好文 > 详细

引用类型对象

时间:2015-06-08 17:00:51      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

1.在方法内修改对象的属性,可以直接对对象进行修改

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

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Attendance a = new Attendance("aaa");
            AA(a);
            Console.WriteLine(a.Name);
            Console.ReadLine();
        }

        public static  void AA( Attendance a)
        {
            //a = new Attendance("dddd");
            a.Name = "eee";
        }
    }

    public class Attendance
    {
        public Attendance(string Name)
        {
            this.Name = Name;
        }
        public string Name { get; set; }
        public DateTime AttendanceDate { get; set; }
    }
}

结果是eee

2.在方法内直接将一个同类实例赋值给该对象,会发现该对象没有任何改变

  class Program
    {
        static void Main(string[] args)
        {
            Attendance a = new Attendance("aaa");
            AA(a);
            Console.WriteLine(a.Name);
            Console.ReadLine();
        }

        public static  void AA( Attendance a)
        {
            a = new Attendance("dddd");
            //a.Name = "eee";
        }
    }

结果还是aaa

 class Program
    {
        static void Main(string[] args)
        {
            Attendance a = new Attendance("aaa");
            AA(a);
            Console.WriteLine(a.Name);
            Console.ReadLine();
        }

        public static  void AA( Attendance a)
        {
            a = new Attendance("dddd");
            a.Name = "eee";
        }
    }

还是aaa

 class Program
    {
        static void Main(string[] args)
        {
            Attendance a = new Attendance("aaa");
            AA(a);
            Console.WriteLine(a.Name);
            Console.ReadLine();
        }

        public static  void AA( Attendance a)
        {
            a.Name = "eee";
            a = new Attendance("dddd");
        }
    }

结果是eee

3.在方法内要对对象进行重新赋值的,可以使用ref,这样就会发现对象就会修改

 class Program
    {
        static void Main(string[] args)
        {
            Attendance a = new Attendance("aaa");
            AA(ref a);
            Console.WriteLine(a.Name);
            Console.ReadLine();
        }

        public static  void AA( ref Attendance a)
        {
            a.Name = "eee";
            a = new Attendance("dddd"); 
        }
    }

结果是dddd

 

引用类型对象

标签:

原文地址:http://www.cnblogs.com/hongdada/p/4561240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!