使用“this()”调用重载方法的正确语法是什么?在 C# 中?
我可能有这个错误,但我已经看到了创建在定义中调用自身的重载方法的方法。它是这样的:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a) : this (a, 10)
{ }
我知道这不是正确的语法,但由于某种原因我无法在任何地方找到正确的语法。正确的语法是什么?
I may have this wrong, but I've seen the way of creating an overloaded method that calls itself in the definition. It's something like:
public void myFunction(int a, int b)
{
//Some code here
}
public void myFunction(int a) : this (a, 10)
{ }
This is not the correct syntax, I know, but I can't find the correct syntax anywhere for some reason. What is the correct syntax for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将构造函数语法与方法语法混淆了。对于方法来说,执行此操作的唯一方法是显而易见的:
尽管从 C#4 开始,您可以使用可选参数:
您编写的内容对于构造函数来说几乎是正确的:
You are confusing constructor syntax for method syntax. The only way to do that for a method is the obvious:
although as of C#4, you can use a optional parameters:
What you wrote is close to right for constructors:
只需这样做:
您将重载与覆盖混淆了。您可以从派生类调用基构造函数,如下所示:
Just do this:
You're confusing overloading with overriding. You can call a base constructor from an derived class like this: