如何在结构体中创建一个方法来显示它的数组?
因此,基本上我遇到的问题是,例如,如果我有如下所示的代码,那么我应该如何在结构中构造方法,以便在调用时显示结构的所有 N 个元素。
struct MyStructure
{
int ID;
string Name;
public Method()
{
?????????
}
}
......程序的主要部分......
MyStructure[] List=New MyStructure[N];
So basically what I got stuck on is if I,for example, have a code like the one shown below then how should I construct the method in the structure in such order that it would display all N elements of structure when called.
struct MyStructure
{
int ID;
string Name;
public Method()
{
?????????
}
}
.....Main Section of program.....
MyStructure[] List=New MyStructure[N];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
单个元素不是数组,除非您执行某些操作使数组可用,否则元素*将有权访问该数组。相反 - 它可以访问自身(又名 `thi
你可以做的就是使方法
静态
:旁注(不相关):我怀疑
struct< /code> 在这里是正确的选择;它很少......总是默认为
class
除非你能确切地说明为什么你将其设为struct< /代码>。
An individual element is not the array, and unless you do something to make the array available, so element *will have access to the array. Rather - it will have access to itself (aka `thi
What you could do is make the method
static
:Side note (unrelated): I doubt that
struct
is the right choice here; it very rarely is... always default toclass
unless you can state exactly why you are making it astruct
.您正在尝试将实例方法添加到数组中包含的项目。使用扩展方法之类的东西可能会更好,例如:
调用为:
您可以只使用普通的静态方法,但我会质疑显示任何信息的过程是否真正与类型本身的目的相关,或者显示是否进程应该留给任何正在消耗你的结构的类型。
You're trying to add an instance method to an item contained within your array. It's probably better to use something like an extension method, e.g.:
Called as:
You could just use a normal static method, but I would question whether the process of displaying whatever information really relates to the purpose of the type itself, or whether the display process should be left to whatever types are consuming your structure.
您可能会追求这样的事情,这确实有一定道理:
这会将您创建的每个实例添加到未附加到特定实例的全局(静态)列表中,然后您可以显示/使用每当您需要时,都可以使用此列表。
正如其他人所说,使用
class
,而不是struct
。What you might be after is such a thing, which does make some sense:
This will add every instance you create to global (static) list that is not attached to specific instance, then you can show/use this list whenever you want.
As others said, use
class
, notstruct
.这是使用结构体执行此操作的另一种方法...
只是简单的链表...
Here is another way how to do it using struct...
just simple linked list...