在C#中如果需要把值类型转换成引用类型传递其他方法中并使其原来值发生改变,使用 ref 和 out 转换成引用类型传递。
1. ref : 使用ref之前需要定义变量并初始化(必须初始)
class Program
{
static void Main(string[] args)
{ int i = 10; //定义变量,并初始化;
Console.WriteLine(" i = " + i); //传递之前打印
Demo(ref i); //通过ref 把 i 改变引用传递
Console.WriteLine(" i = " + i); Console.ReadKey();
} //接收方法参数也要使用 ref 关键字
public static void Demo(ref int i)
{
i = i + 100;
} }
打印结果 :
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOYAAABsCAIAAADxI1lSAAACeElEQVR4nO3dTW7aQACGYe4JuQDpAZoepttuewRfpUmrSk5bQiBAkxp11/ITGyfCxF/yPGI1gplZvBqMHSmD77fVx0+fh+MLL6+I16Cc/RmO3w8ghWQJU86q4fjipXcBrZWzaiRZgpTzanR+ONmiKIqi6G4b+5MX27pbmjDlvBqdfzj4tk672Z98Z0S1/FfO122S7UjdObo54qBlSzlfnzUm+9Rv52JPy488OuLagF3lfH32rr8XBpvhdrQ6YY6e7BFP2Z2zts3qvH59PmWL7cvZjlYnTJ+TPc3qhDmY7DO+6NtrmLy7RcnW8pSFvpAsYSRLGMkSRrKEuZYsWSRLmJbJdn1ztG7y/XH3a9+6PiRbN7mnYjziZX9+1Z2XzeM77znNVumLJz2wbTNhwzPY5o+0Gf834trg7ernn8XUjW8m2/Wu6KmjX8ue4JTdOWvb7IrXI/HnV7F9OdvRruipxGRPsyt66mCyz/iib69u8oZFu9sMGa7vPP0iimQJI1nCSJYwkiWMZAkjWcL8kCxZJEsYyRLmp2TJIlnCSJYwkiWMZAnzayFZokiWMJIljGQJI1nCTCRLlslSskSRLGFuJEsWyRJGsoSZSpYs05VkiSJZwkiWMLeSJctMsmSRLGEkSxjJEma+qiRLkrvfkiWKZAkjWcJIljCLe3cMiCJZwizuXRgQRbKEWUqWLJIljGQJs3yQLFFWD25yEcUdA8L4V3WE+TZ1yhLlq2TJIlnCSJYwkiWMZAlzJVmyXN1IliiSJYxkCSNZwlxKliySJYxkCSNZwkiWMJIljGQJczmRLFEkS5gvkiWLZAkjWcJIljCSJYxkCSNZsvwFVfjYZVLb5cQAAAAASUVORK5CYII=" alt="" />
2. out : 使用out之前需要定义变量,不必初始化;初始化留给被调用方法里进行。
class Program
{
static void Main(string[] args)
{ int i ; //定义变量[不必初始化],如果这里进行了初始化,在接收方法会被替换掉;
Demo(out i); //通过 out 把 i 改变引用传递
Console.WriteLine(" i = " + i); Console.ReadKey();
} //接收方法参数也要使用 out 关键字
public static void Demo(out int i)
{
i = 100; //使用out 方式初始工作在方法内部进行
i = i + 200; //把 i + 200 = 300
} }
打印结果如下:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHwAAABJCAIAAABwy9X3AAACj0lEQVR4nO2YXU/TUACG+9/8ijFKlBDYHCZG41DnZwSV3+Kl114jChb8mOzDWxyOtesmaqZOE1lbduNF21HaHlqU9qXp++S5YKfN6emzQ5dUqih/HLcrynZVtRxU1UFV1WttvdbWa5pR18y6ZtY7PruOHfNDNAMmGamZNbFVy7ZtxXFtpGquqcZ7l2XVKCtGWTHeOb5t7fqmZbze3HV101htGitNY6VpyJ8s9VcjN2yXN/Tlhr7U0Jca+kvHF46LDX3xo+1zlwvr+sL6wFLq9ne+/vY4/H+/hXnQCb94/LXHLZH94VZ/+NnrTnfkT9tOkJrlD9v2XlXL78Eqbnu2rZ7Z6pnSk6fPpoqzbnPFORqrUq44J5GEyc88RC8hezA6gPzMI/QSskeuGB5dlmVZluO4uuxCNO4+JBpPGVPXwh8vMd2he1rR3+6PovH0MXFlFr0ESQr7AvzR073ZL1x6sM/Rg/4vyz4iLiMwumce0Xj6OJu/F3pOrLfnz+eOKwU9XvwbP2WcnrgTeg5kp4du8BRHP3n+Vug5CdxeYHTPIdF4+jg+Vgo9J6bbExX0XE60tVMc/di5/aL/8+MiIqKZRReNdTHJcSLCTieHzKnx2+glZI8zk3fRS8geY4X76CVkj/HLR+I1QLaYvMr36YkT5dUuOWQuXn+MXkL2KNyYRy8hexRuMnriTJcYPXEYHQCjA2B0AIwOYLo0739pnu631UcfRgfA6AAYHQB/SAEwOgBGB8DoABgdAKMDYHQAjA6A0QEwOgBGB8DoABgdAKMDYHQAjA6A0QEwOgBGB8DoABgdAKMDYHQAjA6A0QEwOgBGB8DoABgdAKMDYHQAjA6A0QEwOgBGB8DoABgdAKMnz1++vylF8LwY8QAAAABJRU5ErkJggg==" alt="" />