Getting the type of a MemberInfo with reflection(通过反射获取 MemberInfo 的类型)
问题描述
我正在使用反射来加载具有项目类结构的树视图.类中的每个成员都有一个分配给他们的自定义属性.
I'm using reflection to load a treeview with the class structure of a project. Each of the members in a class have a custom attribute assigned to them.
使用 MemberInfo.GetCustomAttributes()
获取类的属性没有问题,但是我需要一种方法来确定类成员是否是自定义类,然后需要对其自身进行解析返回自定义属性.
I don't have a problem getting the attributes for a class using MemberInfo.GetCustomAttributes()
however I need a way of working out if a class member is a custom class and then needs parsing itself to return the custom attributes.
到目前为止,我的代码是:
So far, my code is:
MemberInfo[] membersInfo = typeof(Project).GetProperties();
foreach (MemberInfo memberInfo in membersInfo)
{
foreach (object attribute in memberInfo.GetCustomAttributes(true))
{
// Get the custom attribute of the class and store on the treeview
if (attribute is ReportAttribute)
{
if (((ReportAttribute)attribute).FriendlyName.Length > 0)
{
treeItem.Items.Add(new TreeViewItem() { Header = ((ReportAttribute)attribute).FriendlyName });
}
}
// PROBLEM HERE : I need to work out if the object is a specific type
// and then use reflection to get the structure and attributes.
}
}
是否有一种简单的方法可以获取 MemberInfo 实例的目标类型,以便我可以适当地处理它?我觉得我遗漏了一些明显的东西,但我现在正在绕圈子.
Is there an easy way of getting the target type of a MemberInfo instance so I can handle it appropriately? I feel I'm missing something obvious but I'm going round in circles at the minute.
推荐答案
GetProperties
返回一个 PropertyInfo
数组,所以你应该使用它.
那么使用 PropertyType
属性.
GetProperties
returns an array of PropertyInfo
so you should use that.
Then it is simply a matter of using the PropertyType
property.
PropertyInfo[] propertyInfos = typeof(Project).GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
// ...
if(propertyInfo.PropertyType == typeof(MyCustomClass))
// ...
}
这篇关于通过反射获取 MemberInfo 的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过反射获取 MemberInfo 的类型


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01