通过引用传递与返回类实例
根据标题,将引用类型传递给方法有什么区别,例如:
public void GetStream(Stream outputStream)
{
outputStream.Write(data);
}
VS
public Stream GetStream()
{
MemoryStream ms = new MemoryStream();
ms.Write(data);
return ms;
}
我注意到很多 Java 代码通过引用传递类(不确定其确切原因)。然而在 .NET 中这只是一个偏好问题吗?
你什么时候会选择其中之一而不是另一个?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两者非常不同。在您的第一个示例中,调用者负责创建一个流(他们喜欢的任何类型),并且可以传递已经位于某个任意位置的流。
在第二个例子中,被调用者已经确定了流的类型,并且始终在位置 0 处写入。
如果您的第一个示例是相反:
它们至少会更接近可比较。
在这里,主要区别在于调用者必须有一个声明的变量来捕获
outputStream
,而在其他情况下,调用者可以忽略返回的流值。然而,第二种形式(返回值)更常见 - 如果一个方法有一个返回值,那么最好是该方法返回该值,而不是一个
out 参数的 >void 方法 - 大多数情况下,在 .NET 中,应该谨慎使用
out
参数(并且仅当该方法的返回值已经是有用的东西)。此类方法的一个示例是各种类型的TryParse
方法,该方法返回bool
(表示成功),并且解析的值作为传回输出参数。
The two are very different. In your first example, the caller is responsible for creating a stream (of whatever kind they prefer), and may pass a stream that is already positioned at some arbitrary position.
In the second, the callee has determined the type of stream, and is always writing at position 0.
If your first example was instead:
they would at least be closer to comparable.
Here, the major difference is that the caller has to have a declared variable to capture the
outputStream
, whereas in the other case, the caller could ignore the returned stream value.However, the second from (returning the value) is more commonly seen - if a method has a single value to return, it's by far preferred that that value is returned by the method, rather than a
void
method with anout
parameter - mostly, in .NET,out
parameters should be used sparingly (and only if the return value from the method is already something useful). An example of such a method would be theTryParse
methods on various types, that return abool
(indicating success), and the parsed value is passed back as anout
parameter.首先,“关注点分离”的概念表明名为“GetStream”的方法也不应该写入流。特别是当“字节”不是传入参数时。这实际上是两个独立的函数,应该以这种方式编码。
但对于最初的问题,通过引用传递仅仅意味着该方法可以选择修改对象的实例。使用返回值返回新的或现有的引用是编写不可变对象的一个步骤,并且绝对值得考虑作为一种实现。
First, the concept of "separation of concerns" suggests that a method called "GetStream" should not also write to the stream. Especially when "bytes" is not an incoming argument. This is really two separate functions, and should be coded that way.
But for the original question, passing by reference simply means that the method has the option of modifying an instance of an object. Using the return value to return a new, or existing, reference, is a step towards writing immutable objects, and is definitely worth considering as an implementation.