Skip to main content
 首页 » 编程设计

c#之当参数是 C# 中的值或引用类型时调用函数

2024年02月20日13mfrbuaa

public class A 
{ 
void methodA(int a){} 
void methodA(ref int a){} 
} 
 
 static void Main() 
  { 
    int a=1; 
    new classA().methodA(a); 
  } 

在主类中,调用了哪个方法? A类中的方法是否重载?可以基于值或引用参数进行覆盖吗?请帮忙让我清楚。

请您参考如下方法:

修复代码后:

public class ClassA 
{ 
    public void methodA(int a)  
    { 
        Console.WriteLine("Without ref"); 
    } 
 
    public void methodA(ref int a)  
    { 
        Console.WriteLine("With ref"); 
    } 
} 
 
class Program 
{ 
    static void Main(string[] args) 
    { 
        int i = 1; 
        var a = new ClassA(); 
 
        a.methodA(i); 
        a.methodA(ref i); 
 
        Console.ReadKey(true); 
    } 
} 

您会看到第一个调用将打印“Without ref”,第二个调用将打印“With ref”。您本可以自己完成。

manual说这是完全可能的:

However, overloading can be done when one method has a ref or out parameter and the other has a value parameter, as shown in the following example.

class RefOverloadExample 
{ 
    public void SampleMethod(int i) { } 
    public void SampleMethod(ref int i) { } 
}