使用反射来引用财产 [英] refer property using reflection

查看:81
本文介绍了使用反射来引用财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用下面的代码使用反射来引用.vb文件winform中定义的testprop属性



Dim testinstance As Object = Activator.CreateInstance(Formname.GetType )



Dim oPropertyInfo As System.Reflection.PropertyInfo = objtype.GetProperty(testprop)



oPropertyInfo.GetValue(testinstance,Nothing)





当我尝试读取属性值时,虽然我先前设置了它,但它显示为null 。当我将此属性声明为共享时,它会显示我设置的值。



任何人都可以提供有关如何在不声明共享修饰符的情况下获取属性值的信息吗? />


谢谢

I am trying to refer the testprop property defined in .vb file winform using reflection using code below

Dim testinstance As Object = Activator.CreateInstance(Formname.GetType)

Dim oPropertyInfo As System.Reflection.PropertyInfo = objtype.GetProperty("testprop")

oPropertyInfo.GetValue(testinstance, Nothing)


When I try to read the property value, it show the null though I set it previously. When I declared this property as shared then it shows the value that I set.

Can anyone provide info on how to get the property value without declaring shared modifier?

Thanks

推荐答案

嗯...你不能。

你正在创建该类的实例:

Um...you can't.
You are creating an instance of the class:
Dim testinstance As Object = Activator.CreateInstance(Formname.GetType)



这是表单的新实例,而不是对任何现有表单的引用。

所以当你获得新实例的属性值时:


Which is a new instance of the form, not a reference to any existing form.
So when you get the property value of the new instance:

oPropertyInfo.GetValue(testinstance, Nothing)

它返回默认值,因为没有其他值已经设定了。



我不禁想到你正在尝试做一些非常简单的事情以一种非常复杂的方式。你到底想要达到什么目的?你为什么在这里使用反射?可能有一种更简单的方法,特别是如果您想要访问表单的existign实例的属性。

it returns the default value as no other value has been set.

I can't help thinking you are trying to do something very simple in a very complicated way. What exactly are you trying to achieve? Why are you using reflection here? There may be a simpler way, particularly if you are tying to access properties of existign instances of your form.


这篇关于使用反射来引用财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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