Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

Pass a data structure to a function and access the fields of the data structure like an array in 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...