列表作为“out”参数导致错误。为什么?
在此代码中:
public bool SomeMethod(out List<Task> tasks)
{
var task = Task.Factory.StartNew(() => Process.Start(info));
tasks.Add(task);
}
我收到错误“使用未分配的输出参数‘任务’”。为什么?
在 MSDN 示例中,仅使用了 out
参数
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
,是因为 List
吗?
In this code:
public bool SomeMethod(out List<Task> tasks)
{
var task = Task.Factory.StartNew(() => Process.Start(info));
tasks.Add(task);
}
I get an error, "Use of unassigned out parameter 'tasks'". Why?
In an MSDN example there's just use of out
parameter
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
Is it because of List<T>
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须在方法主体中初始化
out
参数(即创建一个新的List
实例并将其分配给out
参数):我使用集合初始值设定项语法将任务添加到列表中,但如果您愿意,也可以调用
Add
方法。您应该这样调用该方法:
C# 7.0 引入了新的更简单的语法,您可以使用
out
参数在函数调用中声明变量:作为
List
通过引用传递,您可以去掉out
参数。然后,您必须在调用该方法之前创建列表:并像这样调用它:
一般来说,避免使用
out
参数是一种很好的做法,因为它们可能会造成混淆。You have to initialize the
out
parameter in the method body (that is create a newList<Task>
instance and assign it to theout
parameter):I'm using the collection initializer syntax to add the task to the list, but you could call the
Add
method instead if you prefer.You should call the method like this:
C# 7.0 has introduced new simpler syntax where you declare the variable in the call to the function with the
out
parameter:As a
List<T>
is passed by reference you can get rid of theout
parameter. You then have to create the list before calling the method:And call it like this:
In general it is good practice to avoid
out
parameters because they can be confusing.out
表示您的方法需要创建对象,然后将其分配给参数:out
means that your method needs to create the object, then assign it to the parameter:这是因为您没有为
tasks
变量分配值...在本例中,该值将是对List
类型实例的引用。将
tasks = new List();
添加到 SomeMethod 的主体中,一切都会正常工作:It's because you didn't assign a value to the
tasks
-variable... in this case that would be a reference to a instance of typeList<Task>
.Add
tasks = new List<Task>();
to the body of SomeMethod and everything will work fine:您需要初始化
tasks
参数。例如tasks = new List()
此线程讨论了带有参数的
out
和ref
的使用。如果您使用ref
关键字,那么您必须在调用该方法之前设置该值。不过,我认为在这种情况下没有理由使用ref
关键字You need to initialise the
tasks
parameter. e.g.tasks = new List<Task>()
This thread discusses the use of
out
andref
with parameters. If you use theref
keyword then you must have set the value prior to calling the method. I see no reason to use theref
keyword in this case though您需要执行
tasks = new List();
才能向其中添加 Task 对象。 MSDN 有一个更接近的示例对于你正在做的事情,这传递了一个数组而不是一个 int 。You need to do
tasks = new List<Task>();
before you can add a Task object to it. MSDN has an example that is closer to what you're doing, this passes an array rather than an int.