C#中构造函数的返回类型是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8893959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the return type of a constructor in C#?
提问by sonu thomas
I have asked this question for Java on thislink
我在此链接上为 Java 提出了这个问题
I got some answers in java.Now i want to know it in C#.
我在 java 中得到了一些答案。现在我想在 C# 中知道它。
As we know the we do not have to add any return type to a C# constructor.
正如我们所知,我们不必向 C# 构造函数添加任何返回类型。
class Sample{
.....
Sample(){
........
}
}
In Objective C, if we create a constructor, it returns a pointer to its class. But it is not compulsory, I think.
在 Objective C 中,如果我们创建一个构造函数,它会返回一个指向它的类的指针。但我认为这不是强制性的。
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??
类似地,构造函数是否转换为返回对其自身类的引用的方法?
Like this:
像这样:
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?
编译器是否向构造函数添加了对同一类的引用的返回类型?构造函数发生了什么?任何参考研究这个?
采纳答案by InBetween
According to the C# 4.0 Language Specification, section 1.6:
根据C# 4.0 语言规范,第 1.6 节:
Instances of classes are created using the
newoperator, which allocates memory for a new instance, invokes a constructor to initialize the instance, and returns a reference to the instance.
类的实例是使用
new运算符创建的,该运算符为新实例分配内存,调用构造函数来初始化实例,并返回对实例的引用。
It is the newoperator 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:
这是new谁负责分配内存,传递新分配的对象的参考构造函数,然后返回实例的引用的运营商。该机制也在第 7.6.10.1 节中解释:
The run-time processing of an object-creation-expressionof the form
new T(A), whereTis class-typeor a struct-typeandAis an optional argument-list, consists of the following steps:
If
Tis a class-type:
A new instance of class
Tis allocated. If there is not enough memory available to allocate the new instance, aSystem.OutOfMemoryExceptionis thrown and no further steps are executed.All fields of the new instance are initialized to their default values (§5.2).
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.[…]
形式 的对象创建表达式的运行时处理
new T(A),其中T是类类型或结构类型并且A是可选的 参数列表,包括以下步骤:
如果
T是类类型:
T分配了一个新的类实例。如果没有足够的可用内存来分配新实例,System.OutOfMemoryException则抛出 a 并且不执行进一步的步骤。新实例的所有字段都初始化为其默认值(第 5.2 节)。
根据函数成员调用规则(第 7.5.4 节)调用实例构造函数。对新分配的实例的引用会自动传递给实例构造函数,并且可以从该构造函数内部访问该实例
this。[…]
This would mean that the constructor per sehas no return type (void).
这意味着构造函数本身没有返回类型 ( void)。
回答by Jon Hanna
It depends on how you look at it.
这取决于你怎么看了。
"Return type" is as much conceptual as anything else.
“返回类型”与其他任何东西一样具有概念性。
At the level of the semantics in which C# expresses a programmers intent, constructors don't have return types. They don't even have void. They've no more got a return type than you do.
在 C# 表达程序员意图的语义级别,构造函数没有返回类型。他们甚至没有void。他们没有比你更多的返回类型。
The IL those constructors will be compiled to, have a return type of void.
这些构造函数将被编译为 IL,返回类型为void.
If you invoke a ConstructorInfoyou get an object of the type in question (though the type of the return on that invoke is objectand you have to cast to the type concerned).
如果您调用 a ,ConstructorInfo您将获得相关类型的对象(尽管该调用的返回类型是object,您必须转换为相关类型)。
The closest thing to a concrete meaning to return is the details of how the stack gets manipulated by the constructor being called. Here though you could argue that while a reference type "returns" a reference of the appropriate type, since it places the value in the stack, a value type doesn't since it manipulates the values already present on the stack. Or you could just argue that both are implementation details, and not really answering the question at all.
最接近返回的具体含义的是被调用的构造函数如何操作堆栈的细节。在这里虽然您可能会争辩说,虽然引用类型“返回”了适当类型的引用,因为它将值放在堆栈中,但值类型不会,因为它操作堆栈中已经存在的值。或者你可以争辩说两者都是实现细节,根本没有真正回答这个问题。
"Doesn't have a return type" is probably the most "C#ish" of the above ways of looking at the question.
“没有返回类型”可能是上述看待问题的方式中最“C#ish”的。
回答by afrischke
InBetween's answer is correct. I too disagree with what was discussed in the MSDN forum. If we look at a very simple code sample like the one below:
InBetween 的答案是正确的。我也不同意 MSDN 论坛中讨论的内容。如果我们看一个非常简单的代码示例,如下所示:
void Main()
{
var a = new A();
var message = a.GetAs();
}
public class A {
private readonly string someAs;
public A()
{
someAs = "AaaaaAAAAAaaAAAAAAAaa";
return;
}
public String GetAs()
{
return someAs;
}
}
and the corresponding IL:
和相应的IL:
IL_0000: newobj UserQuery+A..ctor
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: callvirt UserQuery+A.GetMessage
A.GetMessage:
IL_0000: ldarg.0
IL_0001: ldfld UserQuery+A.someAs
IL_0006: ret
A..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ldarg.0
IL_0007: ldstr "AaaaaAAAAAaaAAAAAAAaa"
IL_000C: stfld UserQuery+A.someAs
IL_0011: ret
then it becomes immediately clear, that the .ctor returns void. (This can also been seen easily if you tryto return something from the constructor, i.e. if you do something like public A() { return this; }the compiler will complain and say something like "Since A() returns void, a return keyword must not be followed by an object expression.")
然后立即变得清晰, .ctor 返回void。(如果您尝试从构造函数返回某些内容,这也很容易看出,即如果您执行诸如public A() { return this; }编译器之类的操作,编译器会抱怨并说“由于 A() 返回 void,return 关键字后不能跟对象表达式” .”)
Further: You can see that this expression new A()gets translated to the following IL: newobj UserQuery+A..ctor. The "Common Language Infrastructure Reference" says the following about newobj(section 4.20):
进一步:您可以看到此表达式new A()被转换为以下 IL: newobj UserQuery+A..ctor。“公共语言基础设施参考”对newobj(第 4.20 节)说如下:
The newobj instruction allocates a new instance of the class associated with constructor and initializes all the fields in the new instance to 0 (of the proper type) or null as appropriate. It then calls the constructor with the given arguments along with the newly created instance. After the constructor has been called, the now initialized object reference is pushed onto the stack.
newobj 指令分配与构造函数关联的类的新实例,并将新实例中的所有字段初始化为 0(适当类型)或 null。然后它使用给定的参数以及新创建的实例调用构造函数。构造函数被调用后,现在初始化的对象引用被压入堆栈。
(By way of comparison with Objective-C: new/newobj is the analog to the allocmessage and the constructor the analog to the initmessage.)
(通过与 Objective-C 的比较:new/newobj 是alloc消息的类比,构造函数是init消息的类比。)
So it really is the newoperator that returns a reference to the newly constructed object, not the constructor itself.
因此new,返回对新构造对象的引用的确实是运算符,而不是构造函数本身。

