简体   繁体   English

如何测试反射字段的类型是否为或继承自指定类型

[英]How to test if a reflected field's type is, or inherits from, a specified type

I am iterating through the FieldInfo of a class. 我正在迭代类的FieldInfo I want to be able to test if a given field is of a certain type. 我希望能够测试给定字段是否属于某种类型。

The specific issue is that I want to know all fields that are derived from SortedList . 具体问题是我想知道从SortedList派生的所有字段。 So they are not exactly SortedList , but each one IS a SortedList . 所以它们并不完全是SortedList ,但每一个都是一个SortedList Given the field's FieldInfo , how do I test this? 鉴于该字段的FieldInfo ,我该如何测试?

您可以使用IsAssignableFrom方法执行此测试,如下所示:

var isSortedList = typeof(SortedList).IsAssignableFrom(fieldInfo.FieldType);
bool canCast = (fieldInfo.FieldType == typeof(SortedList) ||
               (fieldInfo.FieldType.IsSubclassOf(typeof(SortedList)));
if ((fieldInfo.FieldType == typeof(SortedList)) || fieldInfo.FieldType.IsSubclassOf(typeof(SortedList))
    Console.WriteLine("Field {0} is of type {1}", fieldInfo.Name, typeof(blah.Name));

This code is untested but is roughly what I have used before. 这段代码未经测试,但大致是我之前使用过的。

Instead of looking for the SortedList as the type, you can also look for interfaces such as IDictionary, ICollection which SortedList derives from. 您可以查找SortedList派生自的IDictionary,ICollection等接口,而不是查找SortedList作为类型。 I provide an interesting read on my blog which gives an example of reflecting for an interface: 我在我的博客上提供了一个有趣的读物,它给出了一个反映界面的例子:

Reflect Interface from Unknown Assembly in C# 在C#中反映来自未知程序集的接口

HTH (From HR down south of you ;-) ) HTH(从你以南的HR ;-))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM