问题描述
我在我们的应用程序中发现了一些代码,通过引用传递一个 List
以指示它被修改:
I found some code in our app that passes a List<T>
by reference to indicate it is modified:
void DoSomething(ref List<MyType> theList)
{
theList.Add(new MyType());
}
我认为很明显在这种情况下 ref-keyword 已经过时了,因为我们也可以在没有关键字的情况下向列表中添加新元素.然而,它表明我们修改了列表或至少它的元素.如果您有很多参数并且想查看其中哪些被修改,哪些只是作为值传递来完成工作,我发现这特别有用.
I think it is clear that the ref-keyword is obsolete in this case, as we could also add new elements to the list without the keyword. However it indicates that we modify the lists or at least its elements. I find this is particulary useful if you have many parameters and want to see which of them are modified and which are just passed as values to do the job.
这个问题是否可以肯定是基于意见的,对 SO 来说是无效的,我宁愿问是否有另一种方法来实现这一点,或者我是否应该关心它.
The question if this is okay is surely opinion-based and would be invalid for SO, I rather ask if there´s another approach to achieve this or if I even should care about it.
稍微澄清一下我的问题.如果列表被修改,这个问题不,这只是一个例子.或者,我也可以使用任何其他引用类型,而不仅仅是 List
.
To clarify my question a bit. This question is not on if a list is modified, this was just an example. Alternatively I´d also use any other reference-type, not just a List<T>
.
推荐答案
不,它没有.它表示可以更改参考.在我看来,使用 ref
关键字作为标识符"可以改变某些东西是不好的,因为它打开了你可能不想要的门.
No, it does not. It indicates the reference can be changed. Using a ref
keyword as 'identifier' something can change is bad in my opinion since it opens doors you might not want.
如果您可以为方法参数分配属性,我建议您研究面向方面的编程.通过新的 Roslyn 编译器及其代码分析服务,您甚至可以检查代码是否违反了给定的原则.
I would advice to look into aspect-oriented programming, were you can assign attributes to method parameters. From the new Roslyn compiler with its code analysis services you could even check if the code violates the principal given.
这篇关于通过引用传递reference-type 表示将被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!