确定Type是否为匿名类型

xyz*_*xyz 24 .net c# anonymous-types .net-3.5 c#-3.0

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

Ric*_*nco 37

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 单声道这个`type.FullName.Contains("AnonymousType");`不是真的. (2认同)

T. *_*ter 14

匿名类型对象的属性

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

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

  • 谢谢,选择返回类型。NameSpace == null; 将我的程序处理提高了近 50%(使用这种方法:http://stackoverflow.com/questions/2483023/how-to-test-if-a-type-is-anonymous) (2认同)

Jar*_*Par 5

没有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;
}
Run Code Online (Sandbox Code Playgroud)