数据结构:访问成员 [英] Data Structure: Accessing Members

查看:61
本文介绍了数据结构:访问成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,一个简单的数据访问类:

First, a simple data access class:

Public Class MyTestClass

    ' the structure of the records in the data file
    Public Structure FileRecordType
        Dim Index As Integer
        Dim RefIndex As Integer
        Dim Type As Short
        <VBFixedString(75)> Public Title As String
    End Structure

    Dim mRecord As FileRecordType


End Class



显然,真正的实现将具有读取&写入数据,访问字段的属性等...

现在,问题是:

1.是否存在通过名称访问结构成员的方法?我想到的是一个简单的函数,例如:



Obviously, the real implementation will have methods to read & write the data, properties to access the fields, etc...

Now, the questions:

1. Is there a methodology to access the structiure members by name? What I am think of is a simple function like:

Function GetValue(ByVal FieldName as String, ByVal iRecord as FileRecordType) as Object


这将使用字段的名称(作为字符串),并以某种方式在传递的记录中找到关联的字段.我意识到这将在包含结构声明的类的范围内发生.

2.同样,我希望能够扫描"结构并返回字段名称列表.

3.一种在结构内查找字符串类型并返回字段长度的方法.


That will take the name (as a string) of the field and somehow find the associated field in the passed record. I realize this will ahve to occur within the scope of the class taht contains the structure declaration.

2. Similarly, I would like to be able to "scan through" the structure and return a list of the field names.

3. A method to find the string types within the structure and return the length of the field.

推荐答案

这都意味着要使用反射.请学习以下内容:
http://msdn.microsoft.com/en-us/library/f7ykdhsy.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.reflection.aspx [^ ].

但是,请参阅我对该问题的评论.我严重怀疑您是否了解您的目标,并且宁愿警告您不要对解决方案进行无意义的过度设计.

我还警告您不要使用Microsoft.VisualBasic.VBFixedStringAttribute http://msdn.microsoft.com/zh-cn/library/microsoft.visualbasic.vbfixedstringattribute.aspx [
It all means using Reflection. Please learn this stuff:
http://msdn.microsoft.com/en-us/library/f7ykdhsy.aspx[^],
http://msdn.microsoft.com/en-us/library/system.reflection.aspx[^].

However, please see my comment to the question. I seriously doubt that you understand your purpose and would prefer to warn you against pointless over-engineering of your solutions.

I also warned you against using Microsoft.VisualBasic.VBFixedStringAttribute, http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.vbfixedstringattribute.aspx[^], please see my comment to the question again.

—SA


您可以使用像这样的反射概念

You can use concept of reflection like this

Dim fi as FieldInfo[] = typeof(MyTestClass).GetFields(BindingFlags.Public | BindingFlags.Instance)



此数组包含有关Structure中所有公共字段的信息
您可以更改"BindingFlags.Public"此参数以根据需要获取其他字段

有关反射概念的更多信息,请参见



this array contains info about all public fields in the Structure
you can change ''BindingFlags.Public'' this parameter to get other fields as you like

for more information read about reflection concept


这篇关于数据结构:访问成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆