本文介绍了最佳做法问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我看到一位同事在做这样的代码:

I saw one of my collegues doing code like this today:

public static void DoStuffWithList(ref List<myclass> result)



就个人而言,我宁愿这样做:



Personally, I would have preferred doing:

public static List<myclass> DoStuffWithList(List<control> result)




实际上,如果我没记错的话,我的"方法也将列表作为参考参数,并且您应该能够像同事在他的方法中一样使用它.

但是对我来说似乎更干净"是,您输入了一个参数,对其进行了处理,然后在方法returnvalue中将其返回.可能只是我太老了,并且有一种老套的看法...

你怎么看?您是否支持或反对一种方法有什么好的论点?

必须删除代码中的代码标签,因为CP编辑器显然不喜欢List<>.并坚持在代码中插入不需要的标签... [/EDIT]

已将泛型尖括号更改为unicode [/EDIT2]




Actually, if I''m not mistaken, "my" method also takes the list as reference parameter, and you should be able to use it just the same way as my collegue does in his method.

But it seems more "clean" to me that you enter a parameter, do something with it and return it in the methods returnvalue. Could just be that I''m too old, though and have an old way of looking at it...

What do you think? Do you have any good arguments for or against one method or the other?

Had to remove the code tags aound the code, because the CP editor apparently doesn''t like List<> and insists on inserting an unwanted tag in the code...[/EDIT]

Changed Generics angle brackets to unicode[/EDIT2]

推荐答案

List<string> lst = new List<string>();
lst.Add("Fred");
lst.Add("Bob");

Test1(lst);
Test2(ref lst);

private void Test1(List<string> lst)
{
    List<string> newLst = new List<string>();
    newLst.Add("Ted");
    newLst.Add("Ned");
    lst = newLst;
}

private void Test2(ref List<string> lst)
{
    List<string> newLst = new List<string>();
    newLst.Add("Ted");
    newLst.Add("Ned");
    lst = newLst;
}



由于大多数人都使用Add()之类的方法,因此这个问题很少引起注意.和AddRange(newLst);将项目添加到列表中.



This problem is not noticed a lot because most people use methods like Add(); and AddRange(newLst); to add items to a List.


result = new List();
...


那么在第一种情况下,调用者将看不到更改,而在第二种情况下,调用者的变量将被更改以引用新对象.

在此处查看更多 http://www.yoda.arachsys.com/csharp/parameters.html [ ^ ]

还要检查这个简单的例子

http://pastebin.com/sm8niPRD [ ^ ]


then in the first case the caller won''t see the change, whereas in the second case the caller''s variable will be changed to refer to the new object.

check here for more http://www.yoda.arachsys.com/csharp/parameters.html[^]

check this simple example too

http://pastebin.com/sm8niPRD[^]



这篇关于最佳做法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 03:51