Mik*_*ebb 2 c# syntax overloading
我可能有这个错误,但我已经看到了创建一个在定义中调用自身的重载方法的方法.它是这样的:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a) : this (a, 10)
{ }
Run Code Online (Sandbox Code Playgroud)
我知道这不是正确的语法,但由于某种原因我无法在任何地方找到正确的语法.这个的正确语法是什么?
您对方法语法的构造函数语法感到困惑.对方法执行此操作的唯一方法是显而易见的:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a)
{
myFunction(a, 10) ;
}
Run Code Online (Sandbox Code Playgroud)
虽然从C#4开始,您可以使用可选参数:
public void myFunction(int a, int b = 10)
{
//Some code here
}
Run Code Online (Sandbox Code Playgroud)
你写的内容对于构造函数来说是接近正确的:
public class myClass
{
public myClass(int a, int b)
{
//Some code here
}
public myClass(int a) : this (a, 10)
{ }
}
Run Code Online (Sandbox Code Playgroud)
这样做:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a)
{
myFunction(a, 10)
}
Run Code Online (Sandbox Code Playgroud)
你会因重写而混淆重载.您可以从派生类中调用基础构造函数,如下所示:
public MyConstructor(int foo)
:base (10)
{}
Run Code Online (Sandbox Code Playgroud)