本文介绍了当使用C#ref关键字永远是个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我越看生产code参考使用,更滥用我遇到的和更多的痛苦也引起了我。我来恨这个关键字,因为从一个框架建设的角度来看,这似乎很傻。当会是一个好主意,传达给C的概念,你的$ C $用户的也许的改变一个对象的引用/值从他们脚下?

The more I see ref used in production code, the more misuse I encounter and the more pain it causes me. I have come to hate this keyword, because from a framework-building standpoint, it seems silly. When would it be a good idea to communicate to users of your code the notion of maybe changing an object reference/value out from beneath them?

相反,我爱了关键字,我爱得更多,当没有关键字会被用了,在这两种情况下,因为你在使用它们提供的担保。参考在另一方面不保证,除非你将被迫您在传递前初始化参数,即使没有什么可以改变一下吧。

By contrast, I love out keywords and I love even more when no keywords are used at all, in both cases because of the guarantees you're given when using them. Ref on the other hand makes no guarantees, except that you'll be forced to initialize the parameter before you pass it in, even though nothing may be changed about it.

我不是圣人,虽然开发商;我敢肯定,它有实际应用的用途。我只是想知道它们是什么。

I'm no sage developer though; I'm sure it's got practically applicable uses. I'd just like to know what they are.

推荐答案

框架设计指南(一本由克日什托夫·Cwalina和布拉德·艾布拉姆斯)建议,以避免这两个 REF 退出参数。

The Framework Design Guidelines (a book by Krzysztof Cwalina and Brad Abrams) recommend to avoid both ref and out parameters.

避免使用退出 REF 参数。

使用退出 REF 参数需要使用指针的经验,了解如何值类型和引用类型的区别和处理方法有多个返回值。此外,在的区别了 REF 参数不甚了解。框架的建筑师设计了一个普通观众不应该指望用户掌握使用制定 REF 参数。

Using out or ref parameters requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between out and ref parameters is not widely understood. Framework architects designing for a general audience should not expect users to master working with out or ref parameters.

该框架设计指南引用的规范交换方法,从有效的异常:

The Framework Design Guidelines cite the canonical Swap method as a valid exception:

void Swap<T>(ref T obj1, ref T obj2)
{
    T temp = obj1;
    obj1 = obj2;
    obj2 = temp;
}

但在同一时间评论言论

but at the same time a comment remarks

交换总是出现在这些讨论中,但我没有写code,实际上需要一个交换的方法,因为大学。除非你有一个很好的理由,避免退出 REF 完全

这篇关于当使用C#ref关键字永远是个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 10:58