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

发布于 2024-12-22 16:54:39 字数 215 浏览 4 评论 0 原文

我正在迭代类的 FieldInfo 。我希望能够测试给定字段是否属于某种类型。

具体问题是我想知道从 SortedList 派生的所有字段。所以它们并不完全是 SortedList,但每一个都是一个 SortedList。 给定字段的 FieldInfo,我如何测试它?

I am iterating through the FieldInfo of a class. 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. So they are not exactly SortedList, but each one IS a SortedList.
Given the field's FieldInfo, how do I test this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

耳根太软 2024-12-29 16:54:39

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

var isSortedList = typeof(SortedList).IsAssignableFrom(fieldInfo.FieldType);

You can use IsAssignableFrom method to perform this test, like this:

var isSortedList = typeof(SortedList).IsAssignableFrom(fieldInfo.FieldType);
逆流 2024-12-29 16:54:39

除了查找 SortedList 作为类型之外,您还可以查找 IDictionary、ICollection 等接口,其中 SortedList 源自。我在我的博客上提供了一篇有趣的读物,其中给出了接口反射的示例:

Reflect Interface from Unknown Assembly in C#< /a>

HTH(来自 HR 南边;-))

Instead of looking for the SortedList as the type, you can also look for interfaces such as IDictionary, ICollection which SortedList derives from. I provide an interesting read on my blog which gives an example of reflecting for an interface:

Reflect Interface from Unknown Assembly in C#

HTH (From HR down south of you ;-) )

卷耳 2024-12-29 16:54:39
if ((fieldInfo.FieldType == typeof(SortedList)) || fieldInfo.FieldType.IsSubclassOf(typeof(SortedList))
    Console.WriteLine("Field {0} is of type {1}", fieldInfo.Name, typeof(blah.Name));

这段代码未经测试,但大致是我之前使用过的。

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.

〆凄凉。 2024-12-29 16:54:39
bool canCast = (fieldInfo.FieldType == typeof(SortedList) ||
               (fieldInfo.FieldType.IsSubclassOf(typeof(SortedList)));
bool canCast = (fieldInfo.FieldType == typeof(SortedList) ||
               (fieldInfo.FieldType.IsSubclassOf(typeof(SortedList)));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文