The ref method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.jedliu(21世纪什么最贵? 人才!)说的比较全了
1. public void Foo(ref ArrayList list); 能够修改指针的指向,可能导致不安全 2. public void Foo(ArrayList list); 仅能修改指向的内容 对于编译器而言,前者拷贝了一份指针,后者直接操作指针。而对于用户而言,将ref用于引用类型,最大的可能就是引入麻烦,有违M$在其c# faq里面屡次提到的原则,但是M$没有禁止或者给出任何的warning,这就是为何我发此一问
----------------------------上面写错了,重发------- 1. public void Foo(ref ArrayList list); 能够修改指针的指向,可能导致不安全 2. public void Foo(ArrayList list); 仅能修改指向的内容 对于编译器而言,后者拷贝了一份指针,前者直接操作指针。而对于用户而言,将ref用于引用类型,最大的可能就是引入麻烦,有违M$在其c# faq里面屡次提到的原则,但是M$没有禁止或者给出任何的warning,这就是为何我发此一问
1. 指针以引用方式传递 public void Foo(ref ArrayList list) { list = new ArrayList(); }ArrayList tempList1 = new ArrayList(); ArrayList tempList2 = tempList1; Foo(ref tempList1);结果:tempList2 != tempList1;2. 指针以值方式传递 public void Foo(ArrayList list) { list = new ArrayList(); }ArrayList tempList1 = new ArrayList(); ArrayList tempList2 = tempList1; Foo(tempList1);结果:tempList2 == tempList1;
能够修改指针的指向,可能导致不安全
2. public void Foo(ArrayList list);
仅能修改指向的内容
对于编译器而言,前者拷贝了一份指针,后者直接操作指针。而对于用户而言,将ref用于引用类型,最大的可能就是引入麻烦,有违M$在其c# faq里面屡次提到的原则,但是M$没有禁止或者给出任何的warning,这就是为何我发此一问
1. public void Foo(ref ArrayList list);
能够修改指针的指向,可能导致不安全
2. public void Foo(ArrayList list);
仅能修改指向的内容
对于编译器而言,后者拷贝了一份指针,前者直接操作指针。而对于用户而言,将ref用于引用类型,最大的可能就是引入麻烦,有违M$在其c# faq里面屡次提到的原则,但是M$没有禁止或者给出任何的warning,这就是为何我发此一问
public void Foo(ref ArrayList list)
{
list = new ArrayList();
}ArrayList tempList1 = new ArrayList();
ArrayList tempList2 = tempList1;
Foo(ref tempList1);结果:tempList2 != tempList1;2. 指针以值方式传递
public void Foo(ArrayList list)
{
list = new ArrayList();
}ArrayList tempList1 = new ArrayList();
ArrayList tempList2 = tempList1;
Foo(tempList1);结果:tempList2 == tempList1;
在Net中,除了基本的类型、数组、结构体等值类型之外,其他类型系统都默认为引用类型,既然是引用类型,那么把它作为参数,必然是引用传递,就是直接操作对象本身。ref的作用主要
是针对值类型的。
传不传ref ,引用虽然都可以返回值,但传ref是可以改变引用地址,不传ref是无法改变引用地址的
对于void Foo(RefTypeA a){}而言,可以传递RefTypeA的子类作为参数。但是对于void Foo(ref RefTypeA a)而言,就不可以传ref sthDerivedFromRefTypeA了。