class1.cs

来自「C#开发教程 由浅入深 配有实例 是初学者的好帮手」· CS 代码 · 共 57 行

CS
57
字号
using System;

namespace RefByOut
{
	class AnotherClass
	{
		public int ID;
	}
	class SomeClass
	{
		// this won't compile
//		public AnotherClass ChangeObject(out AnotherClass ref1)
//		{
//			ref1.ID = ref1.ID*2;
//			return ref1;
//		}
		// this won't compile
//		public AnotherClass ChangeObject(out AnotherClass ref1)
//		{
//			ref1.ID = 4;
//			return ref1;
//		}
		// this won't compile
//		public AnotherClass ChangeObject(out AnotherClass ref1)
//		{
//			int x = ref1.ID;
//			ref1 = new AnotherClass();
//			ref1.ID = x * 2;
//			return ref1;
//		}

		// this WILL compile
		public AnotherClass ChangeObject(out AnotherClass ref1)
		{
			ref1 = new AnotherClass();
			ref1.ID = 99;
			return ref1;
		}
	}

	class RefByOutTest
	{
		[STAThread]
		static void Main(string[] args)
		{
			SomeClass sc = new SomeClass();
			AnotherClass ref1 = new AnotherClass();
			ref1.ID = 3;

			AnotherClass ref2 = sc.ChangeObject(out ref1);
			Console.WriteLine("ref1.ID = {0}, ref2.ID = {1}",
				ref1.ID, ref2.ID);

		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?