通过构造函数和函数创建新对象之间的区别 [英] Difference between creating new object by contructor and by function

查看:111
本文介绍了通过构造函数和函数创建新对象之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

有什么区别

Hi everyone!
What''s difference between

Person p = new Person();
p = PersonService.GetByID(1);







and

Person p = PersonService.GetByID(1);



我不认为他们有所不同.但是有人说他们有所不同.我不明白他们在说什么.请向我解释.



I don''t think they difference. But someone say that they difference. I don''t understand what they say. Please explain to me.

推荐答案

区别在于您要创建多少个实例.在第一个示例中,您正在创建一个新的Person实例.然后,您将使用由指定ID加载的新实例覆盖该实例.在第二个示例中,将使用由指定ID创建的实例加载变量.区别在于第一个实例化.第二个示例是一个实例,而第一个示例是两个实例.

我认为,如果您同时执行这两个语句,则建议以第二种方式进行操作.但是,如果您在第一个示例的第一行和第二行之间有代码行,则建议这样做.原因是因为如果在实例化变量之前尝试使用该变量,则不会收到未设置为对象实例的对象"错误.
The difference is in how many instances you are creating. In the first example, you are creating a new person instance. Then you are overwriting that instance with a new instance that is loaded by the specified ID. In the second example, you are loading the variable with the instance created by the specified ID. The difference is in that first instantiation. The second example is doing one instantiation versus two instantiations of the first example.

In my opinion, I would recommend doing it the second way if you are doing the two statements together. However, if you have lines of code between line one and line two of the first example, I recommend doing it that way. The reason is because then you will not get an "object not set to an instance of the object" error if you try to use the variable before you instantiate it.


这篇关于通过构造函数和函数创建新对象之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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