Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 遍历匿名类型的对象以检索属性和值_.net_Vb.net_Entity Framework_Reflection - Fatal编程技术网

.net 遍历匿名类型的对象以检索属性和值

.net 遍历匿名类型的对象以检索属性和值,.net,vb.net,entity-framework,reflection,.net,Vb.net,Entity Framework,Reflection,使用实体框架(EF6)和VB.Net反射,这两个我现在还不太熟悉 以下是我试图实现的一个简单示例: Dim user as New user() user.full_name = "John Smith" Dim str As String = "The user's name is **full_name**." 'For each p As Property In user.Properties ' str = str.Replace("**" + p.Name + "**", p

使用实体框架(EF6)和VB.Net反射,这两个我现在还不太熟悉

以下是我试图实现的一个简单示例:

Dim user as New user()
user.full_name = "John Smith"

Dim str As String = "The user's name is **full_name**."

'For each p As Property In user.Properties
'    str = str.Replace("**" + p.Name + "**", p.Value)
'Next
输出:用户名是John Smith

但是,问题是
对象
是匿名类型。我希望能够传入任何实体类并动态替换属性引用

我已经尝试了很多,在这里读了很多问题,但我仍然有困难——很明显,我还没有完全理解反思

我将在下面提供我的代码,以及我引用的任何内容。如果有人能把我推向正确的方向,我将不胜感激。谢谢


根据GSerg的评论更新:

Public Function MailMerge(htmlString As String, obj As Object) As String
    Dim keyNames As New List(Of String)

    Dim dictionaryData As New Dictionary(Of String, String)()
    For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
        If p.CanRead AndAlso p.GetIndexParameters().Length = 0 Then
            Dim columnName As String = p.Name

            'FAILS HERE - p.Name is "Item" at the failing iteration
            Dim columnValue = p.GetValue(obj, Nothing)

            dictionaryData.Add(columnName, columnValue)
        End If
    Next

    For Each key In dictionaryData.Keys
        htmlString = htmlString.Replace("**" + key + "**", dictionaryData(key))
    Next

    Return htmlString

End Function
我只得到
容量
计数
作为属性,尽管给定了
用户
类型的对象(从上面),我希望有
全名


EDIT:这个函数还需要处理列表,这显然是我上面提到的问题的根本原因。我将进一步调整它,如果我不能理解它,我将更新我的问题


参考资料:


是索引器,它需要一个参数。显然你不想列举它。如果p.Name“Item”解决我的问题,那么简单的
也能解决吗。。。?据我所知,
Item
本质上是我试图迭代的属性的“兄弟”。虽然我考虑忽略它,但我并不认为这个解决方案太过优雅——我觉得应该有一种更聪明的方法来实现这一点,而不必硬编码名称。不,它不必命名为
。看。@GSerg啊,太好了,这是一个可靠的资源。如果p.CanRead和p.GetIndexParameters().Length=0,我将尝试
并报告back@GSerg没有更多的硬错误,尽管在下一个问题上。我只得到两个非索引器属性:
Count
Capacity
-我是否没有深入到对象中?