Pass a data structure to a function and access the fields of the data structure like an array in C#

﹥>﹥吖頭↗ 提交于 2019-12-13 10:50:17

问题


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
}

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




回答2:


To pass a parameter to a method by reference, you can use the ref keyword. So you could do something like this:

void Method1(Class1 obj1, Class2 obj2, ref Class3 obj3)
{
   obj3 = new Class3();

   // set the fields of obj3 based on values of obj1 and obj2
}

Method1(obj1, obj2, ref obj3);

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.




回答3:


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.



来源:https://stackoverflow.com/questions/6768062/pass-a-data-structure-to-a-function-and-access-the-fields-of-the-data-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!