我们可以不使用构造函数创建对象 [英] can we create object without using constructor

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

问题描述

我们可以创建对象而不使用构造函数

can we create object without using constructor

推荐答案

这取决于你正在构建的内容!



如果它是一个引用类型实例 - 一个 - 那么基本上没有:如果你不提供构造函数,那么系统将为你创建一个空的默认构造函数。当您使用 new 关键字时,将始终调用构造函数 - 并且每次创建引用类型实例时都会这样做,因为这是获得新鲜的唯一方法实例。

That depends on what you are constructing!

If its a reference type instance - a class - then basically, no: if you don't provide a constructor then the system will create an empty default constructor for you. And a constructor will always be called when you use the new keyword - and you do that every time you create a reference type instance because that is the only way to get a "fresh" instance.
MyClass mc;

不调用MyClass构造函数,因为它不会创建类的实例,只是一个在以后创建实例时可以保存对实例的引用的变量。

Does not call the MyClass constructor, because it doesn't create an instance of the class, just a variable that can hold a reference to the instance when it is created later.

MyClass mc = new MyClass();

总是调用构造函数,因为它会创建一个实例。



如果它是值类型 - 基本类型,如 int double bool struct - 那么你不需要创建或调用构造函数。只需创建实例就足够了:

Always calls a constructor as it does create an instance.

If it's a value type - an basic type such as int, double, bool, or a struct - then you don't need to cretae or call a constructor. Just creating the instance is sufficient:

int i = 42;
MyStruct ms;

这两个都创建值类型实例,而不调用构造函数。您可以使用 new 关键字为值类型调用构造函数:

These both create value type instances, without calling a constructor. You can call a constructor for a value type by using the new keyword:

MyStruct ms = new MyStruct();

但您不必这样做。


这篇关于我们可以不使用构造函数创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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