在没有类实例的情况下获取PropertyInfo

问题描述 投票:0回答:2

我已经开始使用反射,并且对于获得PropertyInfo有点困惑。

我做这样的事情,它的工作原理:

Dim x as New MyClass
Dim prop as PropertyInfo = x.GetType.GetProperty("Name")

我不明白为什么我必须有一个类的实例才能从中获取属性。如果GetType返回一个Type对象,为什么我不能只引用该类型本身?

Dim prop as PropertyInfo = GetType(MyClass).GetProperty("Name")

要么

Dim prop as PropertyInfo = MyClass.GetType.GetProperty("Name")
vb.net reflection
2个回答
1
投票
Dim prop as PropertyInfo = GetType(MyClass).GetProperty("Name")

这是完全正确的。


0
投票

一种更安全的方式:

Dim prop as PropertyInfo = GetType(MyClass).GetProperty(NameOf(MyClass.MyProperty))
© www.soinside.com 2019 - 2024. All rights reserved.