将数据结构传递给函数并像 C# 中的数组一样访问数据结构的字段
我有一组不同类型的字段,我必须将它们分组到任何数据结构中。然后我必须将其传递给函数并使用索引修改数据结构的字段,例如数组。 我该怎么做?谢谢大家。
mytype{
int a;
ushort b;
string c;
}
我想传递这个对所有这些字段进行分组的数据结构,它可以是类或结构。并将其传递给一个函数,并希望使用索引修改该实例的字段,如下所示:
void function(ref mytype G)
{
G[1] = 1; <= Here G.a should be set to 1
}
I have a set of fields of different types, I must group them into any data structure. Then I have to pass it to a function and modify the fields the data structure with indexes, like array.
How would I do this? Thanks to everyone.
mytype{
int a;
ushort b;
string c;
}
And I would like to pass this data structure that groups all these fields, it can be class or struct. And Pass this to a function and would like to modify the fields of that instance with indexes, like this:
void function(ref mytype G)
{
G[1] = 1; <= Here G.a should be set to 1
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用对象列表:
但是,如果您这样做,您将失去 C# 强类型的所有优势。我建议使用具有明确定义的强类型属性的类,除非您确实需要一些通用的东西(您事先不知道有关属性类型的任何信息)。
You could use a list of objects:
You lose all the advantages of C#'s strong-typing if you do this, though. I would suggest using a class with well-defined, strongly typed properties instead, unless you really need something generic (where you don't know anything about the properties' types before-hand).
要通过引用将参数传递给方法,可以使用
ref
关键字。所以你可以这样做:至于“用索引修改数据结构的字段,如数组”,如果需要,你可以将这些索引作为附加参数传递。不过,我必须更多地了解你在做什么才能回答这个问题。
请注意,在上面的示例中,通过引用传递 obj3 的唯一原因是该方法正在创建对象的实例。如果对象已经创建,则不需要通过引用传递。
To pass a parameter to a method by reference, you can use the
ref
keyword. So you could do something like this:As for "modify the fields the data structure with indexes, like array", you could pass those indexes as additional parameters if needed. I would have to know a little more about what you are doing to answer that though.
Note that in the above example, the only reason to pass obj3 by reference is because the method is creating the instance of the object. If the object is already created, then passing by reference isn't needed.
修改对象相当容易,只要不将其传递到某些边界(进程、机器、网络(机器的变体))即可。您可以使用 ref 关键字传入,但在大多数情况下没有必要。
然而,这实际上取决于数据结构的含义。您是在谈论您创建的实际对象还是数据集中的数据行(您在 EF 中创建的内容)?
概念是一样的。如果跨越边界,最好“重置”对象而不是尝试通过引用传递。
就您的意思提供一些指导,我可以跟进更具体的信息。
Modifying an object is fairly easy, as long as you are not passing it across certain boundaries (process, machine, network (variation of machine)). You can pass in using the ref keyword, but it is not necessary in most instances.
It really depends on what you mean by data structure however. Are you talking actual objects you have created or data rows in a dataset, something you created in EF?
The concept is the same. If you pass across a boundary, you are better to "reset" your object than try passing by reference.
Give some guidance on your meaning and I can follow up with more specific information.