如何使用 C# 中的任务将值分配给对象的 属性
How to assign Values to a Property of an object using Task in C#
我有一个模型 Class,每个 属性 都映射到一个模型 Class。
考虑模型 Class "Contact
"
public class Contact
{
public Profile profileInfo { get; set; }
public bool isActive { get; set; }
}
public class Profile
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
与任务相关的 C# 代码是
public void MapContact(ref Contact contactInfo)
{
List<Task> taskList = new List<Task>();
taskList.Add(Task.Factory.StartNew(() =>
{
contactInfo.profileInfo = client.GetProfileInfo(1);
}));
Task.WaitAll(taskList.ToArray());
}
我收到以下编译时错误“无法在匿名方法、lambda 表达式或查询表达式 中使用 ref 或 out 参数 'contactInfo'”声明
contactInfo.profileInfo = client.GetProfileInfo(1);
请帮助我如何在没有任何编译时错误的情况下有效地使用 Task。
附上截图
只需声明一个相同类型的局部变量 Contact 并将此局部变量传递给该任务
C#代码:
public void MapContact(ref Contact contactInfo)
{
List<Task> taskList = new List<Task>();
Contact pro = contactInfo;
taskList.Add(Task.Factory.StartNew(() =>
{ pro.profileInfo = new Profile()
{
FirstName = "Stack",
LastName = "Overflow"
};
}));
Task.WaitAll(taskList.ToArray());
}
LinqPad 输出是
我有一个模型 Class,每个 属性 都映射到一个模型 Class。
考虑模型 Class "Contact
"
public class Contact
{
public Profile profileInfo { get; set; }
public bool isActive { get; set; }
}
public class Profile
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
与任务相关的 C# 代码是
public void MapContact(ref Contact contactInfo)
{
List<Task> taskList = new List<Task>();
taskList.Add(Task.Factory.StartNew(() =>
{
contactInfo.profileInfo = client.GetProfileInfo(1);
}));
Task.WaitAll(taskList.ToArray());
}
我收到以下编译时错误“无法在匿名方法、lambda 表达式或查询表达式 中使用 ref 或 out 参数 'contactInfo'”声明
contactInfo.profileInfo = client.GetProfileInfo(1);
请帮助我如何在没有任何编译时错误的情况下有效地使用 Task。
附上截图
只需声明一个相同类型的局部变量 Contact 并将此局部变量传递给该任务
C#代码:
public void MapContact(ref Contact contactInfo)
{
List<Task> taskList = new List<Task>();
Contact pro = contactInfo;
taskList.Add(Task.Factory.StartNew(() =>
{ pro.profileInfo = new Profile()
{
FirstName = "Stack",
LastName = "Overflow"
};
}));
Task.WaitAll(taskList.ToArray());
}
LinqPad 输出是