类上的C#数组-访问一个元素的所有实例 [英] C# Array on Class - access all instances of one element
本文介绍了类上的C#数组-访问一个元素的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C#的新手,想知道是否有一种方法可以传入所有出现的数组声明的类元素吗?
换句话说-
New to C# and want to know if there is a way to pass in all occurrences of of an array declared class element?
In other words -
class something()
{
string a;
string b;
}
class abc()
{
protected void main()
{
something s[] = new something[5]
... initialize array
CallRoutine(something.a[]) or
CallRoutine(something[].a)
}
protected void CallRoutine(string[] receiver)
{
loop through string array...
}
}
推荐答案
应该是这样的:
It should be like this:
public class Something()
{
public string a;
piblic string b;
}
public class Abc()
{
public void main()
{
Something[] s = new Something[5];
//... initialize array
CallRoutine(s);
}
protected void CallRoutine(Something[] receiver)
{
foreach(Something s in receiver)
{
// do something with s an instance of Something here
}
}
}
可以理解吗?如果不发表评论.
干杯!
Understandable? If not leave a comment.
Cheers!
那么,您是否要传递数组的''a''
成员?如果是这样,您将无法获得任何内置功能.您必须创建一个包含所有a
的数组才能通过.但这破坏了整个目的.您如何知道哪个a
属于哪个object
?虽然可以使用索引,但为什么要继续努力呢?
传递您的数组,并以您的方法可以执行任何您想做的事情.
So are you trying to pass the''a''
members of the array? If so, there is nothing you can get build-in. You have to create an array of alla
''s to pass. But that defeats the whole purpose. How would you know whicha
belong to whichobject
? While you can use the index why go all the hard way.
Pass your array and in your method you can do what ever you want to do.
something s[] = new something[5]
... initialize array
CallRoutine(something)
在这里,我对您的要求的解释与曼弗雷德所做的不同.我将假设您要传递一个string
数组,该数组包含通过提取something.a
或something.b
获得的所有字符串.如果是这样,您可以使用LINQ进行此操作.这是一个示例:
Here''s an answer where I''ve interpreted your requirement differently to what Manfred did. I am going to assume you want to pass astring
array consisting of all the strings obtained by extracting eithersomething.a
orsomething.b
. If so, you can do this using LINQ. Here''s an example:
class something
{
public string a;
public string b;
}
class abc
{
public static void CallRoutine(string[] receiver)
{
}
}
class Program
{
static void Main(string[] args)
{
something[] s = new something[5];
// init data
abc.CallRoutine(s.Select(it => it.a).ToArray());
}
}
这篇关于类上的C#数组-访问一个元素的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文