如何测试类型是否是匿名的?

下面的方法将对象序列化为 HTML 标记。我只想这样做,但如果类型不是匿名的。

private void MergeTypeDataToTag(object typeData)
{
if (typeData != null)
{
Type elementType = typeData.GetType();


if (/* elementType != AnonymousType */)
{
_tag.Attributes.Add("class", elementType.Name);
}


// do some more stuff
}
}

谁能告诉我怎么做到这一点?

谢谢

20770 次浏览

检查 CompilerGeneratedAttributeDebuggerDisplayAttribute.Type

下面是编译器为一个匿名类型生成的代码

[CompilerGenerated, DebuggerDisplay(@"\{ a = {a} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<a>j__TPar>
{
...
}

来自 http://www.liensberger.it/web/blog/?p=191:

private static bool CheckIfAnonymousType(Type type)
{
if (type == null)
throw new ArgumentNullException("type");


// HACK: The only way to detect anonymous types right now.
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
&& type.Attributes.HasFlag(TypeAttributes.NotPublic);
}

编辑:
使用扩展方法的另一个链接: < a href = “ https://stackoverflow. com/questions/1650681/確定-if-a-Type-is-an-onymous-Type”> 確定 Type 是否是 Anonymous Type

速战速决:

if(obj.GetType().Name.Contains("AnonymousType"))

现在,编译器将匿名类型生成为泛型和密封类。一个矛盾的组合,因为泛型类的专门化是一种继承,不是吗? 你可以看看这个: 1. 这是泛型类型吗? 是 = > 2)它的定义是密封的 & & amp? Yes = > 3)它的定义是否具有 CompilerGeneratedAttribute 属性? 我想,如果这三个标准放在一起是正确的,我们有一个匿名类型..。 好吧... 有一个问题与任何描述的方法-他们是使用方面,可能在下一个版本的变化。NET,直到 Microsoft 将 IsAnonymous 布尔属性添加到 Type 类。希望在我们都死之前..。 在那天之前,可以这样检查:

using System.Runtime.CompilerServices;
using System.Reflection;


public static class AnonymousTypesSupport
{
public static bool IsAnonymous(this Type type)
{
if (type.IsGenericType)
{
var d = type.GetGenericTypeDefinition();
if (d.IsClass && d.IsSealed && d.Attributes.HasFlag(TypeAttributes.NotPublic))
{
var attributes = d.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false);
if (attributes != null && attributes.Length > 0)
{
//WOW! We have an anonymous type!!!
return true;
}
}
}
return false;
}


public static bool IsAnonymousType<T>(this T instance)
{
return IsAnonymous(instance.GetType());
}
}

您只需检查命名空间是否为空。

public static bool IsAnonymousType(this object instance)
{


if (instance==null)
return false;


return instance.GetType().Namespace == null;
}