c#

位置:IT落伍者 >> c# >> 浏览文章

.net程序员的盲点(一):ref,out ,params的区别


发布日期:2018年07月05日
 
.net程序员的盲点(一):ref,out ,params的区别

C#中有三个关键字refout params虽然本人不喜欢这三个关键字因为它们疑似破坏面向对象特性但是既然m$把融入在c#体系中那么我们就来认识一下参数修饰符refout params吧还有它们的区别

NO params

一个可以让方法(函数)的拥有可变参数的关键字

原则在方法声明中的 params 关键字之后不允许任何其他参数并且在方法声明中只允许一个 params 关键字

示例(拷贝到vs中即可用下面不再说明)

public partial class Form : Form

{

public static void UseParams(params int[] list)

{

string temp = ;

for (int i = ; i < listLength; i++)

temp = temp + +list[i]ToString();

MessageBoxShow(temp);

}

public static void UseParams(params object[] list)

{

string temp = ;

for (int i = ; i < listLength; i++)

temp = temp + + list[i]ToString();

MessageBoxShow(temp);

}

public Form()

{

InitializeComponent();

}

private void button_Click(object sender EventArgs e)

{

UseParams( ); //看参数是

UseParams( ); //看参数是可变吧

UseParams( a test);

int[] myarray = new int[] { };

UseParams(myarray); //看也可以是容器类可变吧

}

}

NO out

这是一个引用传递L

原则一当一个方法(函数)在使用out作为参数时在方法中(函数)对out参数所做的任何更改都将反映在该变量中

原则二当希望方法返回多个值时声明 out 方法非常有用使用 out 参数的方法仍然可以返回一个值一个方法可以有一个以上的 out 参数

原则三若要使用 out 参数必须将参数作为 out 参数显式传递到方法out 参数的值不会传递到 out 参数

原则四不必初始化作为 out 参数传递的变量因为out 参数在进入方法(函数)时后清空自己使自己变成一个干净的参数也因为这个原因必须在方法返回之前为 out 参数赋值(只有地址没有值的参数是不能被net接受的)

原则五属性不是变量不能作为 out 参数传递

原则六如果两个方法的声明仅在 out 的使用方面不同则会发生重载不过无法定义仅在 ref 和 out 方面不同的重载例如以下重载声明是有效的

class MyClass

{

public void MyMethod(int i) {i = ; }

public void MyMethod(out int i) {i = ; }

}

而以下重载声明是无效的

class MyClass

{

public void MyMethod(out int i) {i = ; }

public void MyMethod(ref int i) {i = ; }

}

有关传递数组的信息请参见使用 ref 和 out 传递数组

NO ref

ref仅仅是一个地址!!!

原则一当一个方法(函数)在使用ref作为参数时在方法中(函数)对ref参数所做的任何更改都将反映在该变量中

原则二调用方法时在方法中对参数所做的任何更改都将反映在该变量中

原则三若要使用 ref 参数必须将参数作为 ref 参数显式传递到方法ref 参数的值可以被传递到 ref 参数

原则四ref参数传递的变量必须初始化因为ref参数在进入方法(函数)时后还是它自己它这个地址指向的还是原来的值也因为这个原因ref参数也可以在使用它的方法内部不操作

原则六如果两种方法的声明仅在它们对 ref 的使用方面不同则将出现重载但是无法定义仅在 ref 和 out 方面不同的重载例如以下重载声明是有效的

class MyClass

{

public void MyMethod(int i) {i = ; }

public void MyMethod(ref int i) {i = ; }

}

但以下重载声明是无效的

class MyClass

{

public void MyMethod(out int i) {i = ; }

public void MyMethod(ref int i) {i = ; }

}

有关传递数组的信息请参见使用 ref 和 out 传递数组

示例

public static string TestOut(out string i)

{

i = out b;

return return value;

}

public static void TestRef(ref string i)

{

//改变参数

i = ref b;

}

public static void TestNoRef(string refi)

{

// 不用改变任何东西这个太明显了

refi = on c;

}

public Form()

{

InitializeComponent();

}

private void button_Click(object sender EventArgs e)

{

string outi; //不需要初始化

MessageBoxShow(TestOut(out outi)); //返回值

//输出return value;

MessageBoxShow(outi); //调用后的out参数

//输出out b;

string refi = a; // 必须初始化

TestRef(ref refi); // 调用参数

MessageBoxShow(refi);

//输出ref b;

TestNoRef(refi); //不使用ref

MessageBoxShow(refi);

//输出ref b;

}

               

上一篇:.NET中获取电脑名、IP地址及用户名方法

下一篇:深入.NET托管堆(managedheap)(1)