C#简单的分析 ref 与out的使用
2016-12-08 14:15
405 查看
首先在项目中的使用,注意事项。
主要是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)
{
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);
Console.WriteLine(f);
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);
Console.WriteLine(f);
Console.ReadLine();
}
public static void Example(int i)
{
i=8;
}
public static void Example(ref int i) {
i++;
}
主要是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)
{
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);
Console.WriteLine(f);
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);
Console.WriteLine(f);
Console.ReadLine();
}
public static void Example(int i)
{
i=8;
}
public static void Example(ref int i) {
i++;
}
相关文章推荐
- C#中使用ref和out一点认识!
- C#中ref和out的使用小结
- c#学习体会:使用 ref 和 out 传递数组(downmoon)
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- c#中out和ref的使用区别 [转]
- C#中使用ref和out一点认识!
- *C#中使用ref和out一点认识!*
- c#中out和ref的使用级区别
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref out,关键是string的使用事宜zzpart
- C#Trick&Tip: 使用 ref 与 out 传递参数的区别
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中ref和out的使用小结
- C#中使用ref和out一点认识