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

标签 c#

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) { }
}

关于c# - 当参数是 C# 中的值或引用类型时调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12721963/

相关文章:

c# - 如何在 Delphi 中使用 C# 创建的 DLL

c# - 有没有办法通过 SMB 共享上的创建时间来枚举文件?

c# - 哈希算法.ComputeHash

c# - 如何用空字符串替换出现的 "-"?

c# - 如何使用最新的 Roslyn API 添加引用(C# 脚本执行)

c# - 实现个人用户帐户和 Azure AD 身份验证

c# - 理解调度队列

c# - 是否有类似于 C#/.net 的 jEval 的东西?

C# 处理另一个窗体中对话框的按钮单击

c# - AutoFac 和 CustomPrincipal