如何获取类中所有公共变量的列表? (C#)
我有一个包含很多公共变量的类,我需要能够获取它们的列表。
这是我的班级的一个例子:
public class FeatList: MonoBehaviour {
public static Feat Acrobatic = new Feat("Acrobatic", false, "");
public static Feat AgileManeuvers = new Feat("Agile Maneuvers", false, "" ); void Start(){}}
除了还有大约 100 个变量。有没有可能的方法将所有这些成员变量放入一个可管理的数组中?还是我把自己搞砸了?
I have a class that has A LOT of public variables and I need to be able to get a list of them.
Here's an example of my class:
public class FeatList: MonoBehaviour {
public static Feat Acrobatic = new Feat("Acrobatic", false, "");
public static Feat AgileManeuvers = new Feat("Agile Maneuvers", false, "" ); void Start(){}}
Except there are about 100 more variables. Is there any possible way to get all these member variables in one manageable array? Or have I screwed myself over?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您在变量NAMES之后 - 那么这将为您提供它们:
但如果您想要VALUES,那么这将起作用:
if you're after the varaible NAMES - then this will give them to you:
but if you want the VALUES, then this will work:
如果“变量”指的是类字段(如类级别的变量),您可以使用反射来获取访问权限,就像在这个 MSDN Microsoft 示例中使用 FieldInfo 类(有关详细信息,请参阅 MSDN 链接)
而不是查询在此示例中,您可以从 Main 方法中的
FieldInfoClass
中选择您的FeatList
类。逻辑不需要位于同一类的主方法中。您可以将您的逻辑版本放置在要查询的实体外部,实际上可以使用这种逻辑查询任何对象或类。这些字段是私有的、公共的还是其他字段并不重要——通过反射,您可以访问所有这些字段。
请参阅 MSDN 示例代码 FieldInfo.GetValue( ..) 方法(MSDN 链接) 了解如何使用反射提取字段的值。
If by "Variables" you mean class fields (like variables at the class level) you can use reflection to get access, like in this MSDN Microsoft example using the FieldInfo class (see MSDN link for more info)
Instead of querying the
FieldInfoClass
in this example from the Main method you can choose yourFeatList
class. The logic does not need to be in a main method of the same class. You can place your version of the logic external to the entity you want to query and in fact query any object or class with this kind of logic.It doesn't matter if the fields are private or public or something else - through reflection you can get access to all of them.
See the MSDN sample code at FieldInfo.GetValue(..) method (MSDN link) for how to extract the field's value using reflection.
这将返回一个包含 Feat 类型的所有公共字段的 FieldInfo 数组:
然后您可以像这样读/写字段:
当然,GetValue 返回无类型对象,因此您需要根据需要将其转换为正确的类型。
This will returns an FieldInfo array of all public fields of Feat type:
Then you may read/write fields like this:
Of cource, GetValue returns untyped object, so you need to cast it to the correct type on demand.