vb.net 属性反射 - 如何获得价值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22157952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:58:17  来源:igfitidea点击:

Property reflection - How to get value?

vb.netlinqentity-framework

提问by don_mega

I have a need to get properties and their values dynamically. My code below is failing. Can someone give me a hand? I have tried numerous examples but nothing so far.

我需要动态获取属性及其值。我下面的代码失败了。有人可以帮我吗?我已经尝试了很多例子,但到目前为止还没有。

        Dim seriesName As String = s.SeriesName
        If model.Settings.ShowNativeLanguage Then

            Dim propInfo As System.Reflection.PropertyInfo = s.GetType().GetProperty(model.Country)
            seriesName = CStr(propInfo.GetValue(s, Nothing))

        End If

This code produces the error "Object does not match target type."

此代码产生错误“对象与目标类型不匹配”。

采纳答案by peter

The question was already answered here for C# Object does not match target type using C# Reflection

这里已经回答了这个问题,因为 C# Object does not match target type using C# Reflection

The solution is to change this line of your code:

解决方案是更改这行代码:

seriesName = propInfo.GetValue(propInfo, Nothing).ToString()

to this:

对此:

seriesName = propInfo.GetValue(s, Nothing).ToString()

You need to pass the object of which you want to get the value. (More information in MSDN)

您需要传递要获取其值的对象。(更多信息在MSDN 中

Update:

更新:

You should always check reflection results for Nothingvalues. So first store the output of propInfo.GetValue(s, Nothing)in a temporary variable and later on only call the ToString()-function if the object is not Nothing

您应该始终检查Nothing值的反射结果。所以首先将 的输出存储propInfo.GetValue(s, Nothing)在一个临时变量中,然后ToString()如果对象不是,则仅调用-functionNothing

回答by x0n

Surely that should be:

当然应该是:

 ... propInfo.GetValue(s) ...

Normally you must pass the object representing the thisinstance as the first parameter. You are getting that error because it's expecting the instance s, not a PropertyInfoinstance.

通常,您必须将表示this实例的对象作为第一个参数传递。您收到该错误是因为它期待的是 instance s,而不是PropertyInfoinstance 。