你不知道的ref out
写法一:
public class MyClass
{
public static void Main()
{
sCopy copy =new sCopy();
string a="a";
string b ="b";
string c;
copy.CopyXy( a,b);
Console.WriteLine(a??null);
Console.WriteLine(b??null);
int ia =0;
int ib =1;
copy.CopyInt( ia,ib);
Console.WriteLine(ia);
Console.WriteLine(ib);
Console.ReadKey();
}
}
public class sCopy
{
public string CopyXy( string a,string b)
{
return a=b;
}
public int CopyInt( int a,int b)
{
return a =b;
}
}
方法CopyXy,CopyInt是想分别实现两个拷贝string,int
但是,上面代码返回的结果是
a
b
0
1
显然,这不是我们想要的结果
改进后的写法,写法二:
public class MyClass
{
public static void Main()
{
sCopy copy =new sCopy();
string a="a";
string b ="b";
string c;
copy.CopyXy(ref a,b);
Console.WriteLine(a??null);
Console.WriteLine(b??null);
int ia =0;
int ib =1;
copy.CopyInt(ref ia,ib);
Console.WriteLine(ia);
Console.WriteLine(ib);
Console.ReadKey();
}
}
public class sCopy
{
public string CopyXy(ref string a,string b)
{
return a=b;
}
public int CopyInt(ref int a,int b)
{
return a =b;
}
}
现在的结果是
b
b
1
1
这才是我们想要的结果,其中用了ref,保证实现的是引用传递参数,而之前的方法是值传递,string是引用类型,但是用法和值类型类似
写法三:
public class MyClass
{
public static void Main()
{
sCopy copy =new sCopy();
string a="a";
string b ="b";
string c;
copy.CopyXy(out c,b);
Console.WriteLine(c??null);
Console.WriteLine(b??null);
int ia =0;
int ib =1;
copy.CopyInt(ref ia,ib);
Console.WriteLine(ia);
Console.WriteLine(ib);
Console.ReadKey();
}
}
public class sCopy
{
public string CopyXy(out string a,string b)
{
return a=b;
}
public int CopyInt(ref int a,int b)
{
return a =b;
}
}
结果
b
b
1
1
out和ref都是引用类型传值,只是out不需要初始化,ref需要初始化
补充说明,值类型存放的是有效值,包括:结构体(数值类型,bool型,用户定义的结构体),枚举,可空类型
引用类型放的是对象的引用地址,包括:数组,用户定义的类、接口、委托,object,字符串