如何使用反射确定属性类型? [英] How can I determine property types using reflection?

查看:27
本文介绍了如何使用反射确定属性类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试一个类型的属性,看它是否是指定的类型?

How would I test a property of a type to see if it is a specified type?

我的目标是检查程序集以查看该程序集中的任何类型是否包含 MyType(或从 MyType 继承)的属性.

My goal is to examine an assembly to see if any of the types in that assembly contain properties that are MyType (or inherited from MyType).

这是我走过的路...

AssemblyName n = new AssemblyName();
n.CodeBase = "file://" + dllName;
Assembly a = AppDomain.CurrentDomain.Load(n);

foreach (Type t in a.GetTypes())
    foreach (PropertyInfo pi in t.GetProperties())
        if ( pi.PropertyType is MyType ) // warning CS0184
            Console.WriteLine("Found a property that is MyType");

编译时出现警告 CS0184:给定的表达式永远不是提供的 ('MyType') 类型

This compiles with warning CS0184: The given expression is never of the provided ('MyType') type

推荐答案

您对什么类型感兴趣?方法/属性/事件等的返回类型?

What type are you interested in? The return type of the method/property/event etc?

如果是这样,我认为 MemberInfo 中没有任何内容可以让您直接获得它 - 您需要强制转换并使用 MethodInfo.ReturnType, PropertyInfo.PropertyTypeFieldInfo.FieldTypeEventInfo.EventHandlerType 以及我忘记的任何其他内容.(请记住,类型本身可以是成员.不确定您想用它们做什么!)

If so, I don't think there's anything in MemberInfo to let you get at it directly - you'll need to cast and use MethodInfo.ReturnType, PropertyInfo.PropertyType, FieldInfo.FieldType, EventInfo.EventHandlerType and any others I've forgotten. (Remember that types themselves can be members. Not sure what you'll want to do with them!)

如果您对特定类型是代表 MyType 还是某个子类感兴趣,请使用 Type.IsAssignableFrom:

If you're interested in whether a specific Type represents either MyType or some subclass, then use Type.IsAssignableFrom:

if (typeof(MyType).IsAssignableFrom(type))

现在我们知道您需要属性,这很容易 - 使用 GetProperties 而不是 GetMembers.我喜欢用 LINQ 进行反射:

Now that we know you want properties, it's easy - use GetProperties instead of GetMembers. I like doing reflection with LINQ:

var query = from type in assembly.GetTypes()
            from property in type.GetProperties()
            where typeof(MyType).IsAssignableFrom(property.PropertyType)
            select new { Type=type, Property=property };

foreach (var entry in query)
{
    Console.WriteLine(entry);
}

如果您不喜欢 LINQ:

If you're not a fan of LINQ:

foreach (Type t in a.GetTypes())
    foreach (PropertyInfo pi in t.GetProperties())
        if (typeof(MyType).IsAssignableFrom(pi.PropertyType))
            Console.WriteLine("Found a property that is MyType");

请注意,您可能希望指定绑定标志以获取非公共属性等.

Note that you might want to specify binding flags to get non-public properties etc.

这篇关于如何使用反射确定属性类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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