这是我的课:
public class UnusedRolesOccurrence
{
public string Username { get; set; }
public string FullName { get; set; }
public string Role { get; set; }
public int[] Month { get { return month; } set { month = value; } }
private static int[] month = new int[12];
}
这就是我想用值填充 int 数组的地方:
Parallel.ForEach(unusedrolesoccurrence, (UnusedRolesOccurrence item) =>
{
try
{
lock (listLock)
{
int count = tmp.Count(x => x.Username == item.Username && x.Role == item.Role);
item.Month[month] = count;
if (count > 2)
{
Debug.WriteLine($"{item.Username},{item.Role},{month}={count},{item.Month[month]}");
}
}
}
catch
{
//
}
});
List<unusedrolesoccurrence>预先填充了数据。在开始 foreach 之前,月份数组是 [0,0,0,0,0,0,0,0,0,0,0,0],使用int[] arr_month = new int[12];.
tmp也是一个List<t>。
什么不工作:在循环期间,计数和值item.Month[month]也是正确的。但不在目标中List<UnusedRolesOccurrence>。所有月份都是循环中处理的最后一个计数的相同值,例如 [3,0,3,0,0,0,0,0,0,0,0,0] 或 [0,1,1,0 ,0,0,0,0,0,0,0,0]。而且因为并行,结果当然总是不同的。
我换int[]到public Dictionary<int, int> Month { get; set; }测试,但同样的行为。
这里的示例代码(使用 // 二次尝试使用具有相同结果的字典):
public class UnusedRoles
{
public string Username { get; set; }
public string Role { get; set; }
public int Month { get; set; }
}
public class UnusedRolesOccurrence
{
public string Username { get; set; }
public string Role { get; set; }
//public Dictionary<int, int> Month { get; set; }
public int[] Month { get { return month; } set { month = value; } }
public int[] month = new int[12];
}
public List<UnusedRoles> unusedroles = new List<UnusedRoles>();
public List<UnusedRolesOccurrence> unusedrolesoccurrence = new List<UnusedRolesOccurrence>();
public Form1()
{
InitializeComponent();
}
皈依舞
弑天下
牛魔王的故事
随时随地看视频慕课网APP
相关分类