调用驻留在字典中的对象的方法?(Calling a method of an object that resides within a dictionary?)

编程入门 行业动态 更新时间:2024-10-28 09:28:01
调用驻留在字典中的对象的方法?(Calling a method of an object that resides within a dictionary?)

我有一个包含int和Resource类型的对象的字典。 Resource对象包含一个名为CreateNode()的方法。 如果我写这样的foreach循环:

foreach (var resourcePair in ResourceDictionary) { // call CreateNode() on each Resource object in dictionary pair }

如何在字典中的每个资源对象上调用CreateNode()方法? 我试过以下,但编辑不喜欢它(说“无法解析符号”)。 这是正确的,因为它看起来我试图调用该对上的CreateNode方法,而不是该对的一部分对象上的CreateNode()方法。

foreach (var resourcePair in ResourceDictionary) { resourcePair.CreateNode(ref xElement); }

我无法弄清楚如何做到这一点。 有人可以向正确的方向提供指针吗?

I have a dictionary that contains an int and an object of type Resource. The Resource object contains a method called CreateNode(). If I write a foreach loop like this:

foreach (var resourcePair in ResourceDictionary) { // call CreateNode() on each Resource object in dictionary pair }

How can I call the CreateNode() method on each Resource object in the dictionary? I've tried the following, but the editor doesn't like it (says "Cannot resolve symbol"). Which is correct since it appears I'm trying to call the CreateNode method on the pair instead of the CreateNode() method on the object that is part of the pair.

foreach (var resourcePair in ResourceDictionary) { resourcePair.CreateNode(ref xElement); }

I just can't figure out how to do this. Can someone offer a pointer in the right direction?

最满意答案

您需要执行以下操作:

foreach (var resourcePair in ResourceDictionary.Values) { resourcePair.CreateNode(ref xElement); }

你需要指定你想访问的值(这是你的资源对象集合),否则你只是访问一个没有CreateNode方法的KeyValuePair。

You need to do the following:

foreach (var resourcePair in ResourceDictionary.Values) { resourcePair.CreateNode(ref xElement); }

You need to specify that you want to access the values (which is your collection of resource objects) otherwise you are just accessing a KeyValuePair that doesnt have a CreateNode method.

更多推荐

本文发布于:2023-07-26 05:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1271326.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   对象   方法   Calling   dictionary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!