[英]Is returning a type pointer the same as 'newing a type'? in c#
Instead of... 代替...
Video v = new Video();
I want to do 我想要做
Video v = GetVideo();
public Video GetVideo()
{
return new Video();
}
Are these two calls totally equal? 这两个电话完全相等吗?
Yes, they are. 对,他们是。 I have used this approach several times to return me an object prepopulated by some default testing values.
我已经多次使用这种方法来返回一个由一些默认测试值预填充的对象。
Is returning a type pointer the same as 'newing a type'?
返回类型指针是否与“更新类型”相同?
It depends on the method returning the object reference. 这取决于返回对象引用的方法。
Your given snippets, for example, are functionally equivalent because GetVideo()
does nothing except return a new Video()
. 例如,给定的代码片段在功能上是等效的,因为
GetVideo()
除了返回new Video()
之外什么也不做。
至少您可以将它们视为相等,如果它们位于相同的程序集中,则它们可能会内联到相同的IL代码。
They're the same in this case because the method also creates a new Video
. 在这种情况下,它们是相同的,因为该方法还会创建一个新的
Video
。 However, consider this instead: 但是,请考虑以下内容:
private Video video;
public Video GetVideo()
{
if (video == null)
{
video = new Video();
}
return video;
}
Now a new Video
object will be created only the first call - subsequent calls will return a reference to the existing object. 现在,仅第一个调用将创建一个新的
Video
对象-后续调用将返回对现有对象的引用。
(That's only a simple example, of course - it could sometimes create a new one, sometimes not, sometimes return null etc.) (当然,这只是一个简单的示例- 有时可以创建一个新示例,有时不创建,有时返回null等。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.