【发布时间】:2016-09-11 20:43:28
【问题描述】:
作为一个新手,我读过关于使用ref 关键字传递参数的危险。我想当 ref 变量在程序的一部分中被修改,然后改变其他地方发生的事情时,很有可能会弄乱代码。对象最终会非常紧密地耦合。 (我认识there may be places where ref is worthwhile。)我还不知道并且正在询问的是替代方案。
例如,在一个程序中,我在启动时创建了一个通用列表,我在程序的方法中对其进行操作。在一种方法中:
//a user is asked a question
//if the response is yes, the list is modified one way and the method returns true
//if the response is no, the list is modified a different way and the method returns false.
所以该方法返回一个布尔值,我将列表作为ref 传递。我有几种类似的方法,每种方法都向用户提出独特的问题,然后以某种方式修改列表。
它似乎 一个典型的替代方案可能是将列表和一个布尔字段捆绑到它自己的类中。不知何故,这似乎只是为了方便而创建一个对象,只是为了保存两条数据,与任何现实世界的实体没有任何联系。
那么,您将如何(伪)编写一个既返回通用列表又返回布尔值的方法?
编辑:这是一些实际的代码
private static bool AskExptQuestion(ref List<StatTest> testList)
{
Console.Write(Constants.ExptQText); //experimental groups?
string response = Console.ReadLine();
//if response==y, it's experimental
if (response == "y")
{
//so select all experimental
var q1List =
from test in testList
where test.isExperimental == true
select test;
//to copy resulting IEnumerable<List> (q1list) to generic List, must copy/cast IEnumerable to a List<t>
testList = q1List.ToList();
return true;
}
//and if response==n, it's not experimental
else
{
//so select all non-experimental
var q1List =
from test in testList
where test.isExperimental == false
select test;
testList = q1List.ToList();
return false;
}
}
【问题讨论】:
-
为什么将列表作为
ref传递?只需将其修改到位,例如与…AddRange? -
先让一些代码工作,然后再担心“危险”。你在这里偏离了轨道。
-
对象已经是传值方式了,不需要使用ref关键字将集合传入方法中进行修改。
-
@AlC:你可以修改变量所引用的object而不改变变量的值。听起来你需要阅读pobox.com/~skeet/csharp/parameters.html
-
另外,请注意引用的“避免使用
out或ref参数。”您链接的问题的答案中的部分很愚蠢。忽略它。
标签: c#