本文介绍了遍历结构体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够遍历C#中的结构的值(.NET 2.0)。这是必须要做的,在运行时,与在该结构没有知识的可能值。

I would like to be able to iterate through the values of a struct in C# (.Net 2.0). This is to be done at runtime, with no knowledge of the possible values in the struct.

我在想沿着或者使用反射到结构值添加到列表或结构转化到实现IEnumerable接口的数据结构的线。任何人都可以提供任何指针?

I was thinking along the lines of either using Reflection to add the struct values to a list, or converting the struct to a data structure that implements the IEnumerable interface. Can anyone provide any pointers?

在此先感谢您的帮助。

问候,安迪。

推荐答案

究竟你的意思是 - 一个结构中的各个领域?或属性吧?如果是这样, Type.GetFields() Type.GetProperties()是要走的路。

What exactly do you mean - the various fields within a struct? Or properties perhaps? If so, Type.GetFields() or Type.GetProperties() is the way to go.

您绝对相信你需要使用一个结构,顺便说一下?这是很少在C#最好的设计决定的,特别是如果该结构包含多个值。

Are you absolutely sure you need to use a struct, by the way? That's rarely the best design decision in C#, particularly if the struct contains multiple values.

编辑:是的,似乎结构被用于传统的原因

Yes, it seems that structs are being used for legacy reasons.

有一件事我没有提到之前:如果结构的字段不公开的,你需要指定适当的BindingFlags(如 BindingFlags.Instance | BindingFlags.NonPublic可

One thing I didn't mention before: if the struct's fields aren't public, you'll need to specify appropriate BindingFlags (e.g. BindingFlags.Instance | BindingFlags.NonPublic).

这篇关于遍历结构体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:47