确定Type是否为匿名类型

在C#3.0中,是否可以确定Type的实例是否代表匿名类型?

即使匿名类型是普通类型,您也可以使用一些启发式:

 public static class TypeExtension { public static Boolean IsAnonymousType(this Type type) { Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0; Boolean nameContainsAnonymousType = type.FullName.Contains("AnonymousType"); Boolean isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType; return isAnonymousType; } } 

另一个好的启发式方法是,如果类名是有效的C#名称(生成的匿名类型没有有效的C#类名 – 请使用正则表达式)。

匿名类型对象的属性

  • 命名空间等于null
  • System.Object的基本类型
  • IsSealed = true
  • 自定义属性0是DebuggerDisplayAttribute,类型:“”
  • IsPublic = false

对于我的特定应用程序,如果命名空间为null,则可以推断该类型是匿名的,因此检查命名空间为null可能是最便宜的检查。

没有C#语言结构允许您说“这是一个匿名类型”。 如果类型是匿名类型,您可以使用简单的启发式方法进行近似,但是可能会被人们手工编码IL,或使用>和<等字符在标识符中有效的语言欺骗。

 public static class TypeExtensions { public static bool IsAnonymousType(this Type t) { var name = t.Name; if ( name.Length < 3 ) { return false; } return name[0] == '<' && name[1] == '>' && name.IndexOf("AnonymousType", StringComparison.Ordinal) > 0; } 

在美沙酮和CLR中没有匿名类型的术语。 匿名类型只是编译器function。

可能有助于知道为什么你想知道这一点。 如果执行以下操作:

 var myType = new { Name = "Bill" }; Console.Write( myType.GetType().Name ); 

…你会看到像“<> f__AnonymousType0`1”这样的输出作为类型名称。 根据您的要求,您可以假设以<>开头的类型包含“AnonymousType”和后引号字符是您正在寻找的类型。

似乎匿名类型在它们上面放置一个DebuggerDisplayAttribute ,其中Type = ""

编辑:但只有在调试模式下编译时。 该死。