小编典典

如何测试类型是否为匿名?[重复]

c#

这个问题已经在这里有了答案

匿名类型-有什么明显的特点吗? (3个答案)

6年前关闭。

我有以下将对象序列化为HTML标签的方法。但是,如果类型不是Anonymous,我只想这样做。

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
    }
}

有人可以告诉我如何实现这一目标吗?

谢谢


阅读 319

收藏
2020-05-19

共1个答案

小编典典

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);
}

编辑:
扩展方法的另一个链接:确定类型是否为匿名类型

2020-05-19