zoukankan      html  css  js  c++  java
  • .net ref关键字在引用类型上的使用

    只接上干货。
    namespace ConsoleApplication1
    {
    	class Person
    	{
    		public string UserName { getset; }
    	}
    	class Program
    	{
    		static void Main(string[] args)
    		{
    			var p = new Person {UserName = "Tom"};
    			ChangePersonData(p);
    			Console.WriteLine(p.UserName);// here will print "TOM" rather than "peter"
     
    			ChangePersonDataByRef(ref p);
    			Console.WriteLine(p.UserName);// now it will print "peter".
    			Console.Read();
    		}
     
    		static void ChangePersonData(Person per)
    		{
    			per = new Person{UserName = "peter"};
    		}
     
    		static void ChangePersonDataByRef(ref Person per)
    		{
    			per = new Person {UserName = "peter"};
    		}
    	}
    }
    
    
    我们知道,如果我们不用ref或者out关键字,那函数参数就是实参的copy.
    在ChangePersonData()中, 参数per就是局部变量p的copy。 在该函数中我们让per指向一个新new出来的Person对象,而对于原先的局部变量p来说是没有变化的,p这时还是指向了原有的Person对象。要想改变p指向的Person对象,我们就应该用ref或者out。因为ref和out会让我们按引用传递函数参数,也就是传递p本身而不是它的copy.
  • 相关阅读:
    Widget Factory
    233 Matrix
    青蛙的约会
    Longge's problem
    密码解锁
    SQFREE
    GCD
    [WC2011]最大XOR和路径
    [HNOI2011]XOR和路径
    [ZJOI2010]排列计数
  • 原文地址:https://www.cnblogs.com/peteryan/p/3791809.html
Copyright © 2011-2022 走看看