什么是C#构造函数的返回类型? [英] What is the return type of a constructor in C#?

查看:530
本文介绍了什么是C#构造函数的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也问过这个问题,对Java在链接

I have asked this question for Java on this link

我在java.Now一些答案,我想知道它在C#。

I got some answers in java.Now i want to know it in C#.

正如我们所知道的,我们没有任何的返回类型添加到C#构造函数。

As we know the we do not have to add any return type to a C# constructor.

class Sample{
  .....
  Sample(){
    ........
  }
}

在Objective C中,如果我们创建一个构造函数,它返回一个指向它的类。但它不是强制性的,我想。

In Objective C, if we create a constructor, it returns a pointer to its class. But it is not compulsory, I think.

AClass *anObject = [[AClass alloc] init];//init is the constructor with return type a pointer to AClass

类似地,被转换成返回到它自己的类??

Similarly, Is the constructor converted to a method which return a reference to its own class??

这样的:

class Sample{
    .....
    Sample Sample(){
      ........

      return this;
    }
}

该编译器添加返回类型相同类的引用来构造器?
什么是发生在一个构造函数?
任何引用研究这个?

Does the compiler add a return type a reference to same class to constructor? What is happening to a constructor? Any reference to study this?

推荐答案

按照 C#4.0语言规范的第1.6节:

类的实例,用创建了新的运营商,这对于一个新的实例分配内存,调用构造函数初始化实例,返回实例的引用。

Instances of classes are created using the new operator, which allocates memory for a new instance, invokes a constructor to initialize the instance, and returns a reference to the instance.

这是运营谁负责分配内存,传递新分配对象的参考构造函数,然后返回实例的引用的。这种机制在第7.6.10.1还解释:

It is the new operator who is responsible of allocating memory, passing a reference of the newly allocated object to the constructor and then returning a reference to the instance. This mechanism is also explained in section 7.6.10.1:

对象创建前pression 的形式的运行时处理
  新T(A),其中 T 类型的或的结构型 A 是一个可选
  的参数列表的,包括以下步骤:

The run-time processing of an object-creation-expression of the form new T(A), where T is class-type or a struct-type and A is an optional argument-list, consists of the following steps:


      
  • 如果 T 类型的:


      
  • 类的新实例被分配 T 。如果没有足够的
      内存来分配新实例,一个
      的System.OutOfMemoryException 被抛出,并没有进一步的步骤
      执行。

  • A new instance of class T is allocated. If there is not enough memory available to allocate the new instance, a System.OutOfMemoryException is thrown and no further steps are executed.

新实例的所有字段初始化为它们的默认
  值(5.2节)。

All fields of the new instance are initialized to their default values (§5.2).

实例构造函数根据调用
  函数成员调用规则(第7.5.4节)。一提到新
  分配的实例会自动传递给实例构造函数
  和实例可以从构造函数中进行访问为这个

The instance constructor is invoked according to the rules of function member invocation (§7.5.4). A reference to the newly allocated instance is automatically passed to the instance constructor and the instance can be accessed from within that constructor as this.

[...]

这将意味着构造的本身的没有返回类型(无效)。

This would mean that the constructor per se has no return type (void).

这篇关于什么是C#构造函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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