将数据结构传递给函数并访问数据结构的字段,如C#中的数组 [英] Pass a data structure to a function and access the fields of the data structure like an array in C#

查看:210
本文介绍了将数据结构传递给函数并访问数据结构的字段,如C#中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组不同类型的字段,我必须将它们分组成任何数据结构。然后我必须将其传递给一个函数,并用数组修改数据结构的索引。
我该怎么做?感谢大家。

  mytype {
int a;
ushort b;
string c;
}

我想传递这些数据结构,将所有这些字段组合起来可以是类或结构体。并将其传递给一个函数,并希望使用索引修改该实例的字段,如下所示:

  void function mytype G)
{
G [1] = 1; < =这里Ga应设置为1
}


解决方案

您可以使用对象列表:

  var list = new List< object>(); 
list.Add(strings are cool!);
list.Add(42);

// ...

var objByIndex = list [1]; // 42

尽管如此,如果您这样做,您将失去C#强力打字的所有优点。我建议使用具有明确定义的强类型属性的类,除非你真的需要一些通用的东西(在这里你不知道属性的类型)。


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
}

解决方案

You could use a list of objects:

var list = new List<object>();
list.Add("strings are cool!");
list.Add(42);

// ...

var objByIndex = list[1];        // 42

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).

这篇关于将数据结构传递给函数并访问数据结构的字段,如C#中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆