确定类是否实现 T4 模板中的通用列表

发布于 2024-09-04 17:35:22 字数 454 浏览 3 评论 0原文

我正在编写一个 T4 模板,它从程序集中加载一些类,对这些类进行一些分析,然后生成一些代码。我需要做的一项特殊分析是确定该类是否实现了通用列表。我可以在 C# 中非常简单地完成此操作,例如,

public class Foo : List<string> { }

var t = typeof(Foo);

if (t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(List<>)))
    Console.WriteLine("Win");

但是 T4 模板使用 FXCop 内省引擎,因此您无法访问 .net 反射 API。我在 Reflector 中度过了过去几个小时,但仍然无法弄清楚。有人知道如何做到这一点吗?

I'm writing a T4 template which loads some classes from an assembly, does some analysis of the classes and then generates some code. One particular bit of analysis I need to do is to determine whether the class implements a generic list. I can do this pretty simply in C#, e.g.

public class Foo : List<string> { }

var t = typeof(Foo);

if (t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(List<>)))
    Console.WriteLine("Win");

However T4 templates use the FXCop introspection engine and so you do not have access to the .net reflection API. I've spent the past couple of hours in Reflector but still can't figure it out. Does anyone have any clues about how to do this?

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

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

发布评论

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

评论(2

空城之時有危險 2024-09-11 17:35:22

我从 http://www.binarycoder.net/fxcop/ 下载了 Introspector (正如我在我的评论),看起来您需要检查 BaseType 或 BaseClass Template。

I downloaded Introspector from http://www.binarycoder.net/fxcop/ (as I mentioned in my comment) and it looks like you need to check BaseType or BaseClass Template.

鸠魁 2024-09-11 17:35:22

想通了,它不是很漂亮,但是使用 AssemblyNode.Load 加载的所有类型都是 TypeNode 类型,要确定该类型是否实现 List,您必须这样做:

node.BaseType.IsGeneric && node.BaseType.Template == FrameworkAssemblies.Mscorlib.Types.SingleOrDefault(t => t.FullName == "System.Collections.Generic.List`1")

希望它对某人有帮助!

Figured it out, it's not very pretty but all type's loaded using AssemblyNode.Load are of type TypeNode, to determine if the type implements List you must do this:

node.BaseType.IsGeneric && node.BaseType.Template == FrameworkAssemblies.Mscorlib.Types.SingleOrDefault(t => t.FullName == "System.Collections.Generic.List`1")

hope it helps someone!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文