欢迎访问 生活随笔!

凯发ag旗舰厅登录网址下载

当前位置: 凯发ag旗舰厅登录网址下载 > 编程语言 > c# >内容正文

c#

java params 关键字-凯发ag旗舰厅登录网址下载

发布时间:2024/9/30 c# 29 豆豆
凯发ag旗舰厅登录网址下载 收集整理的这篇文章主要介绍了 java params 关键字_转载------c# ref 和 out ,params关键字的用法 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

一、ref 的用法——引用

c#提供一种强制按引用传递参数的方法。这种方法既能用在值类型上,也能用在引用类型上。

就是同时在方法的声明和调用上使用 ref 关键字。

using system;

class program

{

static void main()

{

int i = 10;//必须进行初始化,不然编译会报错

fun(ref i);

console.writeline("i = " i);

console.readline();

}

static void fun(ref int i)

{

i = 100;

}

}

输出结果为 : i = 100

二、out 的用法——输出参数

在c 中,获得方法的结果要么是通过返回值,要么是通过由引用或指针传递的参数。

而在c#中,除了返回值,引用,还提供了一种比较正规的方法。就是使用 out 关键字来标记需要返回的参数。

using system;

class myclass

{

public string testout(out string i)

{

i = "使用out关键字";

return "out参数";

}

}

class test

{

static void main()

{

string x;//可以不用初始化,在方法内部赋值即可。

myclass app = new myclass();

console.writeline(app.testout(out x));

console.writeline(x);

console.readline();

}

}

输出结果为:

out参数

使用out关键字

三、params 的用法——不定数目的参数

c 中允许函数带有默认参数,允许不定数目的参数。但c#中不允许函数参数带有默认值。默认值这种功能,只能用函数重载来代替实现了。

但是c#允许方法带有不定数量的参数。使用params关键字,且参数必须是参数表中的最后一个参数。

using system;

class program

{

static void main()

{

fun("call 1");

console.writeline("\n");

fun("call 2", 2);

console.writeline("\n");

fun("call 3", 3.2, "hey look at here", false);

console.readline();

}

static void fun(string str, params object[] args)

{

console.writeline(str);

foreach (object ob in args)

{

if (ob is int)

{

console.write(" int : " ob);

}

else if (ob is double)

{

console.write(" double : " ob);

}

else if (ob is string)

{

console.write(" string : " ob);

}

else

{

console.write(" other type : " ob);

}

}

}

}

输出结果为:

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是凯发ag旗舰厅登录网址下载为你收集整理的java params 关键字_转载------c# ref 和 out ,params关键字的用法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发ag旗舰厅登录网址下载网站内容还不错,欢迎将凯发ag旗舰厅登录网址下载推荐给好友。

  • 上一篇:
  • 下一篇:
网站地图