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.
  • 相关阅读:
    记账本第二天
    记账本第一天
    HDU 1811
    Codeforces Round #246 (Div. 2) D. Prefixes and Suffixes
    KMP超强模板贴一份
    2014辽宁省赛总结
    Codeforces Round #244 (Div. 2)
    CodeForces 383D Antimatter
    NEU 1351 Goagain and xiaodao's romantic story I
    UVA 10692 Huge Mod
  • 原文地址:https://www.cnblogs.com/peteryan/p/3791809.html
Copyright © 2011-2022 走看看