基于名称作为字符串访问 VB 属性 - 最快选项 [英] Access VB property based on name as string - Fastest Option

查看:55
本文介绍了基于名称作为字符串访问 VB 属性 - 最快选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 VB 中开发一个 ASP.NET MVC Web 应用程序,我需要将一组数据输出为表格格式,并允许用户配置可用集中列的顺序和存在.数据集存储为表示行模型的对象类型列表.

I'm developing an ASP.NET MVC web app in VB and I am required to output a set of data to a table format, and to allow the user to configure the order and presence of columns from an available set. The data set is stored as a list of the object type representing the row model.

目前,我使用 CallByName.迭代属性名称的有序列表并从行模型的实例输出值.然而,根据测试,这似乎是该过程中的一个主要瓶颈.

Currently, I implement this using CallByName. Iterating over an ordered list of property names and outputting the value from the instance of the row model. However, based on testing this seems to be a major bottleneck in the process.

我看到过建议存储委托以获取属性,而不是属性名称的字符串表示.所以,我大概可以做这样的事情:

I've seen a recommendation to store delegates to get the property, against the string representation of the property's name. So, I can presumably do something like this:

Public Delegate Function GetColumn(ByRef RowObj As RowModel) As String

Dim GetPropOne As GetColumn = Function(ByRef RowObj As RowModel) RowObj.Prop1.ToString()

Dim accessors As New Hashtable()

accessors.Add("Prop1", GetPropOne)

然后,循环并执行如下操作:

Then, loop through and do something like this:

Dim acc As GetColumn = accessors(ColumnName)

Dim val As String = acc.Invoke(currentRow)

它看起来更快,但看起来也需要更多的维护.如果这确实更快,有没有办法可以动态构建这样的东西?我在想:

It looks faster, but it also looks like more maintenance. If this is indeed faster, is there a way I can dynamically build something like this? I'm thinking:

Public Delegate Function GetObjectProperty(Instance As Object) As Object

For Each prop In GetType(RowModel).GetProperties()
    Dim acc As GetObjectProperty = AddressOf prop.GetValue
    columns.Add(prop.Name, acc)
Next

Dim getColVal As GetObjectProperty = columns(ColumnName)

Dim val As String = getColVal.Invoke(currentRow).ToString()

对不同方法的建议持开放态度.

Open to suggestions for different approaches.

推荐答案

如果 ColumnNameRowModel 的属性之一同名,我看不到为什么你需要与代表的长期解决方法......

If ColumnName is the same name as one of the RowModel's properties I don't see why you need the long workaround with delegates...

扩展方法仅获取您现在想要的属性既更快又消耗更少的内存.

An extension method which gets only the property you want right now is both faster and consumes less memory.

Imports System.Runtime.CompilerServices

Public Module Extensions

    <Extension()> _
    Public Function GetProperty(ByVal Instance As Object, ByVal PropertyName As String, Optional ByVal Arguments As Object() = Nothing) As Object
        Return Instance.GetType().GetProperty(PropertyName).GetValue(Instance, Arguments)
    End Function
End Module

示例用法:

currentRow.GetProperty("Prop1")
'or:
currentRow.GetProperty(ColumnName)

这篇关于基于名称作为字符串访问 VB 属性 - 最快选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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