请解决构造函数问题 [英] please solve the constructor issue

查看:75
本文介绍了请解决构造函数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用VS2010和C#4.我创建了一个控制台应用程序,其中有一个类似于以下内容的类:

I am using VS2010, and C#4. I have created a Console application in which I have a class that looks like this:

class cl
{
  public int a, b;

  public cl()
  {
  }
  public cl(int x = 10, int y = 20)
  {
    this.a = x;
    this.b = y;
  }
  public void add()
  {
    Console.WriteLine(a+b);
  }
}



我是这样从Main函数调用的:



I call this from the Main function like this:

class Program
{
  static void Main(string[] args)
  {
    cl obj = new cl(10);
    obj.add();
    Console.ReadKey();
  }
}

我希望该程序无法编译,因为我在创建类对象时传递了一个参数.

I would expect this program to fail to compile since I am passing a single parameter while creating the class object. Can somebody help me in understanding this behaviour?

推荐答案

之所以没有失败,是因为您在两参数构造函数中提供了默认值.此功能是在C#4中添加的,因此非常合法.您可以在此处找到更多有关命名和可选参数的详细信息 [
The reason it''s not failing is because you are supplying default values in your two-parameter constructor. This feature was added in C#4, so that''s quite legitimate. You can find more details on named and optional parameters here[^].


public cl(int x = 10, int y = 20)

在构造函数中定义某些值时,就是在.Net 4.0中间接定义可选参数.
这样您的代码就可以使用.

AFAIK,如果您使用的是.Net 3.0,则会出现错误.

此处阅读有关可选参数的信息. [
public cl(int x = 10, int y = 20)

When you define some values in the constructor, you are indirectly defining optional parameters in .Net 4.0.
Thus your code works.

AFAIK, if you were using .Net 3.0, you would have got an error.

Read about optional arguments here[^].


这篇关于请解决构造函数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆