C#简单的分析 ref 与out的使用
来源:互联网 发布:mac迅雷会员无法加速 编辑:程序博客网 时间:2024/05/19 09:01
首先在项目中的使用,注意事项。
主要是ref 能够把参数原本值带进函数内,经过一些运算,然后再带出去。(注意参数的值必须在调用之前赋值)
out是先把参数没有进行赋值,带进函数内,首先要经过赋值,接着经过一些运算,然后在带出去。(注意参数的值必须在内部先进行赋值,再操作)
简单的叙述,ref有进有出,out只出不进。
下面是一个简单的举例:
static void Main(string[] args)
{
{
int f = 10 ;
ExampleOut(out f);
Console.WriteLine(f);//此时输出f值为8
ExampleRef(ref f);
Console.WriteLine(f);//此时输出f值为9
Console.ReadLine();
}
public static void ExampleOut(out int i)
{
ExampleOut(out f);
Console.WriteLine(f);//此时输出f值为8
ExampleRef(ref f);
Console.WriteLine(f);//此时输出f值为9
Console.ReadLine();
}
public static void ExampleOut(out int i)
{
i=8;//如果不赋值的话,则会报错。
}
public static void ExampleRef(ref int i) {
i++;
}
再接着写一点,关于类的内部函数重载的注意事项
如果仅是以out,ref做为函数重载的条件化,则会报错。(错误信息:错误 1 无法定义重载方法“Example”,因为它与其他方法仅在 ref 和 out 上有差别)
如下面的例子:
static void Main(string[] args)
{
{
int f ;
Example(out f);
Console.WriteLine(f);
Example(ref f);
Example(out f);
Console.WriteLine(f);
Example(ref f);
Console.WriteLine(f);
Console.ReadLine();
}
public static void Example(out int i)
{
i=8;
}
public static void Example(ref int i) {
Console.ReadLine();
}
public static void Example(out int i)
{
i=8;
}
public static void Example(ref int i) {
i++;
}
请看下面正确的例子。如果一个方法采用 ref 或 out参数,而另一个方法不采用这两个参数,则可以进行重载
static void Main(string[] args)
{
{
int f =1;
Example( f);
Console.WriteLine(f);
Example(ref f);
Example( f);
Console.WriteLine(f);
Example(ref f);
Console.WriteLine(f);
Console.ReadLine();
}
public static void Example(int i)
{
i=8;
}
public static void Example(ref int i) {
Console.ReadLine();
}
public static void Example(int i)
{
i=8;
}
public static void Example(ref int i) {
i++;
}
0 0
- C#简单的分析 ref 与out的使用
- c# ref out 的使用
- C# ref与out关键字的使用与区别
- c#中out ref的简单使用说明
- C#中ref与out的区别
- C# out与ref的区别
- C# 中 ref 与 out 的区别
- c#中ref与out的区别
- c#中Ref与Out的区别
- C# ref与out的异同
- C# ref和out参数的使用
- ref和out的使用与区别
- ref和out的使用与区别
- ref和out的使用与区别
- ref和out的使用与区别
- ref和out的使用与区别
- ref和out的使用与区别
- C#引用类型参数加ref或out与不加ref或out的区别
- MySQL 数据类型介绍
- Matrix Differentiation summary
- 20161208 ADO.NET小记
- 关于git的使用
- fastjson的使用(转自:http://blog.csdn.net/wx_962464/article/details/37612861)
- C#简单的分析 ref 与out的使用
- nanopi2学习
- unix时间戳 为什么计算机时间要从1970年1月1日开始算起?
- android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
- android studio如何使用已创建的tag,切换到tag,在tag基础上修复BUG
- nginx在centos中遇到无法正常启动问题,及mysql修改root用户的密码
- 华为Mate8 ROOT
- Android系统源码阅读(18):Android 应用的显示
- js基础 概念