[英]How can I iterate over a ProcessThreadCollection to access a property of each object inside the collection?
I have a simple loop that attempts to iterate over a ProcessThreadCollection
variable 我有一个简单的循环,尝试对ProcessThreadCollection
变量进行迭代
Inside the loop, I am trying to access a property of each object in the collection like so 在循环内部,我试图像这样访问集合中每个对象的属性
foreach (var thread in Process.GetProcessesByName(processName)[0].Threads)
{
var threadId = thread.Id;
Console.WriteLine(threadId);
}
However, I get an error stating the following 但是,出现以下错误提示
Cannot resolve symbol 'Id' 无法解析符号“ Id”
If I do the following, I can access the Id
property of an object within the collection 如果执行以下操作,则可以访问集合中对象的Id
属性
var threadCollection = Process.GetProcessesByName(processName)[0].Threads;
var threadId = threadCollection[0].Id;
Console.WriteLine(threadId);
How could I change my loop so that I could access the Id
property of each object in the ProcessThreadCollection
? 如何更改循环,以便可以访问ProcessThreadCollection
中每个对象的Id
属性?
Process.Threads
property returns ProcessThreadCollection
which does not implement generic IEnumerable<T>
. Process.Threads
属性返回不实现通用IEnumerable<T>
ProcessThreadCollection
。 Instead, it derives from ReadOnlyCollectionBase
, which in turn implements non-generic ICollection
and IEnumerable
. 相反,它是从ReadOnlyCollectionBase
派生的,后者又实现了非通用的ICollection
和IEnumerable
。
Because of all that, when you defined your loop using var
the type of the loop variable thread
is inferred to be object
. 因此,在使用var
定义循环时,将循环变量thread
的类型推断为object
。
You can work around that in two ways: 您可以通过两种方法解决此问题:
Either explicitly specify the type: 明确指定类型:
foreach (ProcessThread thread in Process.GetProcessesByName(processName)[0].Threads)
or call Cast<ProcessThread>
: 或致电Cast<ProcessThread>
:
foreach (var thread in Process.GetProcessesByName(processName)[0].Threads.Cast<ProcessThread>())
Both of these will make the compiler realize thread
is of type ProcessThread
and not object
and will give you access to all the properties of that type, including Id
. 这两种方法都会使编译器意识到thread
属于ProcessThread
类型而不是object
类型,并使您能够访问该类型的所有属性,包括Id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.