1.out与ref
1.用途
在c#中当一个方法需要返回多个值的时候,就需要用到ref与out
2.相同点
1.都是址传递,执行方法后,原来的值会改变
2.都能返回多个值
3.不同点
1.使用ref时,传入参数必须要初始化,不能为空的引用,而使用out时参数可以不初始化
2.ref的参数可以不赋值,但是out参数必须要赋值,out进入函数时会清空自己,必须在函数内部赋初值
ref有进有出,out只出不进
//ref的使用
class Program
{
static void Main(string[] args)
{
Program p = new Program();
int b = 5;
int b = 10;
//以下a与b未初始化,编译失败
//int a;
//int b;
p.GetNum(ref a, ref b);
Console.WriteLine("a={0},b={1}", a, b);
}
public void GetNum(ref int a, ref int b)
{
a = 500;
b = 1000;
}
}
//输出结果为a=500,b=1000
//out的使用
class Program
{
static void Main(string[] args)
{
Program p = new Program();
int a=5;
int b=10;
p.Swap(out a, out b);
Console.WriteLine("a={0},b={1}", a, b);
}
public void Swap(out int a,out int b)
{
a=500;
b=1000;
int temp = a;
a = b;
b = temp;
}
//以下函数体内a与b未赋值,编译出错
//public void Swap1(out int a,out int b)
//{
// int temp = a;
// a = b;
// b = temp;
//}
}
//输出结果a=1000,b=500
2.new的作用
1.创建对象
2.在派生类中使用new关键字,修饰定义与基类中同名的函数,叫覆盖,覆盖不会改变基类的方法功能
class A
{
public virtual void Test1()
{
Console.WriteLine("A类的测试函数1");
}
public virtual void Test2()
{
Console.WriteLine("A类的测试函数2");
}
}
class B : A
{
//当用子类创建父类的实例时,A a1 = new B();调用子类的函数
//override声明不能更改virtual方法的可访问性,且override方法与virtual方法必须具有相同级别访问修饰符
public override void Test1()
{
Console.WriteLine("B类的测试函数1");
}
//当用子类创建父类的实例时,A a2 = new B();
//覆盖是不会改变父类的功能,仍然调用父类的函数
public new void Test2()
{
Console.WriteLine("B类的测试函数2");
}
}