开发者

Determining whether a class implements a generic list in a T4 template

开发者 https://www.devze.com 2023-01-02 16:25 出处:网络
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 whethe

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 templat开发者_Go百科es 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?


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.


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号